开发者

applying script to elements inserted via jquery .html()

i'm kinda new to scripting so this might be a bit basic, but i couldn't find an answer anywhere. To improve my webpage loading time I made some HTML element load (via AJAX) and inserted only when a certain button is clicked, using the jquery .html() function. That worked, but now all the jquery commands which referred to that element don't seem to apply. I'm guessing it's bec开发者_运维问答ause the original commands were loaded before the new HTML?

For example, code like this:

$(document).ready(function(){   
$('#myButton').click(function(){
$('#placeHolder').html('<div id="touchMe">click me</div>');
});
$('#touchMe').click(function(){
alert ("WORKED");
});
}

How do I make the #touchMe.click command apply to the new incoming HTML?

thanks a lot


Take a look at live()

$('#touchMe').live('click', function() {


Try -

$('#touchMe').live('click',function(){
alert ("WORKED");
});


Instead of

$('#touchMe').click(function(){
alert ("WORKED");
});

use

$('#touchMe').live('click', function(){
alert ("WORKED");
});


you use .live() or .delegate() function instead of click.

$(document).ready(function(){   
  $('#myButton').live('click', function(){
    $('#placeHolder').html('<div id="touchMe">click me</div>');
  });
  $('#touchMe').live('click', function(){
    alert ("WORKED");
  });
}

note: the live on "mybutton" is not necessary in this example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜