问题描述
在我的 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>
它有一个为点击事件注册的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');
});
它将添加一个类,tabclick
到 里面,
和
id="gentab"
.它工作正常.这是我的 代码:
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);
});
对于第一个链接,它工作正常.它正在提醒 id.但是对于第二个
,其中
class="tabclick"
是由第一个 jQuery 添加的,但它不起作用.
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单击事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!