添加类后,jQuery click事件不起作用 [英] jQuery click event not working after adding class
问题描述
在我的JSP页面中,我添加了一些链接:
In my JSP page I added some links:
<a class="applicationdata" href="#" id="1">Organization Data</a>
<a class="applicationdata" href="#" id="2">Business Units</a>
<a class="applicationdata" href="#" id="6">Applications</a>
<a class="applicationdata" href="#" id="15">Data Entity</a>
它具有为click事件注册的jQuery函数:
It has a jQuery function registered for the click event:
$("a.applicationdata").click(function() {
var appid = $(this).attr("id");
$('#gentab a').addClass("tabclick");
$('#gentab a').attr('href', '#datacollector');
});
它将向<a>
中的<li>
内的<a>
添加一个类tabclick
.一切正常.这是我的<li>
代码:
It will add a class, tabclick
to <a>
which is inside <li>
with id="gentab"
. It is working fine. Here is my code for the <li>
:
<li id="applndata"><a class="tabclick" href="#appdata" target="main">Application Data</a></li>
<li id="gentab"><a href="#datacollector" target="main">General</a></li>
现在我为这些链接提供了jQuery点击处理程序
Now I have a jQuery click handler for these links
$("a.tabclick").click(function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
对于第一个链接,它工作正常.它正在警告<li>
id.但是对于第二个<li>
,第一个jQuery添加class="tabclick"
的地方不起作用.
For the first link it is working fine. It is alerting the <li>
id. But for the second <li>
, where the class="tabclick"
is been added by first jQuery is not working.
我尝试了$("a.tabclick").live("click", function()
,但随后的第一次链接点击事件也无法正常工作.
I tried $("a.tabclick").live("click", function()
, but then the first link click event was also not working.
推荐答案
由于class
是动态添加的,因此您需要使用事件委托来注册事件处理程序
Since the class
is added dynamically, you need to use event delegation to register the event handler
$(document).on('click', "a.tabclick", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
这篇关于添加类后,jQuery click事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!