使用 jquery live 点击事件
我有以下脚本,只要是静态 html,它就可以工作
$('li.tab').each(function(index) {
$("#tab" + index ).click(function() {$("#tabs").tabs( "select" , index );});
});
这就是静态 html 的样子:
<div class="item" id="tab0"><div class="icon" style="background-image: url('http://intranet/icon0.png');"></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>
如果我使用数据库通过 jquery/ajax 生成 3 行 html,我是否必须使用 jquery live 函数来连接点击事件在上面的脚本中看起来?
如果是,我该怎么做?
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');"></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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您需要使用live
yes you need to use live
使用 .delegate() 代替 .live(),将其绑定到围绕您的目标对象的对象。您可以链接 .delegate() 并且它具有更好的性能(您可以在此处查找它http://jquerybyexample.blogspot.com/2010/08/bind-vs-live-vs-delegate-function.html)
另外,不要忘记使用 . die()/.undelegate(),否则您将面临触发多个请求的风险(即,如果您的 .live() 声明被多次调用,您的 click 事件将触发多次。您可以在此处查找< a href="https://stackoverflow.com/questions/4588423/jquery-ui-ajax-tabs-requests-multiplying-when-loading-links-within-tabs">jQuery UI ajax 选项卡 - 在加载链接时请求成倍增加tabs)
请注意,jQuery 1.4.2 的 .live() 中有一个错误,请考虑到这一点。
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.