jQuery - How do I get jQuery to function properly after loading a remote page with jQuery in it?

StackOverflow https://stackoverflow.com/questions/19138049

  •  30-06-2022
  •  | 
  •  

jQuery on the current page works.

I loaded a remote page to a div in my current page using:

<div class="row-fluid">
    <ul class="nav nav-tabs">
        <li><a data-toggle="tab" id="spotlight" href="#" data-hvalue="menu1">menu1</a></li>
        <li><a data-toggle="tab" id="spotlight" href="#" data-hvalue="menu2">menu2</a></li>
    </ul>
</div>
<div class="showroom" id="showroom"></div>
    <script>
        $('a#spotlight').click(function () {
        $(this).each(function (){
            if($(this).data('hvalue')=="menu1"){
                $.getScript( "http://calebevans.me/projects/jcanvas/resources/jcanvas/jcanvas.min.js", function() {
                     alert('Load was performed.');
                 });
            }
            var temp = $(this).data('hvalue') + " #page";
            $('#showroom').load(temp);
        });
    });
    </div>
</script>

The remote page has the following code:

<div class="container-fluid" id="page">
    <div class="row-fluid">
        <button id="DrawItem">Draw Item</button>
        <div id="canvases">
            <canvas width="640" height="480"></canvas>
        </div>
    </div>
</div>

At first, I put this snippet in the remote page: $(document).ready(function() { $('a#DrawItem').click(function(){ $("canvas").drawArc({ fillStyle: "black", x: 100, y: 100, radius: 50 }); }); }); But it wouldn't work. I put the canvas and the jcanvas.min.js script into the same page, and everything works. If I try to load the canvas from a remote page, it won't work.

有帮助吗?

解决方案

You can't assign the event handler to the element as you tried, as it doesn't exist at the time. Instead, you can attach it to a container element like this...

$(document).ready(function() {
    $("#showroom").on("click", "#DrawItem", function(){
        $("canvas").drawArc({
          fillStyle: "black",
          x: 100, y: 100,
          radius: 50
        });
    });
});

That will capture click events on #showroom and fire the event handler if the click originated from #DrawItem. This is event delegation and you can read more about it here...

http://api.jquery.com/on/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top