开发者

click event using jquery live

开发者 https://www.devze.com 2023-02-16 23:48 出处:网络
I have the following script which works as long as the are static html $(\'li.tab\').each(function(index) {

I have the following script which works as long as the are static html

$('li.tab').each(function(index) {
    $("#tab" + index ).click(function() {$("#tabs").tabs( "select" , index  );});
});

This is what the static html looks like:

<div class="item" id="tab0"><div class="icon" style="background-image: url('http://intranet/icon0.png');"><开发者_JAVA技巧/div> Default</div>
<div class="item" id="tab1"><div class="icon" style="background-image: url('http://intranet/icon1.png');"></div> Reports</div>
<div class="item" id="tab2"><div class="icon" style="background-image: url('http://intranet/icon2.png');"></div> Other</div>

If I use a database to generate the 3 html lines via jquery/ajax, do I have to use the jquery live function to connect the click event look in the script above?

If yes, how would I do this?


yes you need to use live

$('li.tab').each(function(index) {

  $("#tab" + index).live('click', function() {
    // ...
  });

});


$('.your_target_class').live('click', function () {
    //your code here.
});


Instead of .live(), use .delegate() which you bind to an object that surrounds what you're targeting. You can chain .delegate() plus it's better performance wise (you can look it up here http://jquerybyexample.blogspot.com/2010/08/bind-vs-live-vs-delegate-function.html)

Also, don't forget to use .die()/.undelegate(), otherwise you're running a risk of firing multiple requests (ie, if your .live() declaration gets called multiple times, your click event will fire multiple times. You can look this up here jQuery UI ajax tabs - requests multiplying when loading links within tabs)

Mind you, jQuery 1.4.2 has a bug in it's .live(), take that into account.

0

精彩评论

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

关注公众号