jQuery-事件不会为动态创建的选项卡元素触发 [英] jQuery - events won't fire for dynamically created tab elements

查看:99
本文介绍了jQuery-事件不会为动态创建的选项卡元素触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery UI选项卡.

<div id="tabs">
<ul id="tablist">
    <li><a href="#fragment-1"><span>One</span></a></li>
</ul>
</div>

我有一个添加新标签的按钮.我使用以下代码:

I have a button that adds new tabs. I use the following code:

var newTabId = $('#tabs').tabs('option', 'selected') + 1;    
$('#tabs').tabs("add",'someUrl.htm','New Tab',newTabId);

(选项卡将添加到当前所选标签的旁边)

(Tab will be added next to the currently selected tab)

现在,所有新添加的标签都不会触发任何事件,例如单击或悬停

Now none of the newly added tabs fire any events such as a click or hover

$('#tablist li').click(function(){
    alert('test message');
});

但是事件对于原始源代码中的选项卡正确触发.

But events fire properly for the tabs that were there in the initial source code.

如何解决?

推荐答案

改为使用 live

$('#tablist li').live('click', function(){
    alert('test message');
});

或者更好的是, delegate 事件

Or better yet, delegate the event

$('#tablist').delegate('li', 'click', function(){
    alert('test message');
});

这篇关于jQuery-事件不会为动态创建的选项卡元素触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆