JQuery:以编程方式添加的锚点与我的点击功能无关
我是 JQuery 新手,我正在尝试使用它在旧的 Web 应用程序中实现增强功能。
我从服务器收集字符串列表,并将每个字符串呈现在其自己的锚标记中,以便它们出现在逗号分隔的列表中。我将生成的标记分配给跨度的内部 html:
$.getJSON("http://domain/restOfURL",
function(data){
var anchorString = "";
$.each(data.companies, function(i,companies){
if (i > 0)
{
anchorString += ", ";
}
anchorString += '<a class="sr" href="#">' + companies + '</a>';
});
$("#anchorsListSpan").html(anchorString);
});
});
所有这些都有效,我可以在实时网页上看到锚点。标记在 Firebug 中看起来像这样:
<span id="anchorsListSpan">
<a class="sr" href="#">ABC</a>
,
<a class="sr" href="#">Apple</a>
,
<a class="sr" href="#">Apollo</a>
</span>
我遇到的问题是任何生成的锚点都不会导致我的单击事件触发:
$("a.sr").click(function(){
alert("link clicked");
});
我注意到,如果我在该 div 中硬编码类似的锚点,则单击事件会触发。由于某种原因,我以编程方式添加的事件不会导致单击事件触发。
有人看到我在这里做错了什么吗?
感谢您的帮助,
I'm new to JQuery and I'm trying to use it to implement an enhancement in an old web application.
I'm gathering a list of strings from a server and rendering each one of them in its own anchor tag such that they appear in a comma delimited list. I assign that generated markup to a span's inner html:
$.getJSON("http://domain/restOfURL",
function(data){
var anchorString = "";
$.each(data.companies, function(i,companies){
if (i > 0)
{
anchorString += ", ";
}
anchorString += '<a class="sr" href="#">' + companies + '</a>';
});
$("#anchorsListSpan").html(anchorString);
});
});
All of that works and I can see the anchors on the live web page. The markup looks like this in Firebug:
<span id="anchorsListSpan">
<a class="sr" href="#">ABC</a>
,
<a class="sr" href="#">Apple</a>
,
<a class="sr" href="#">Apollo</a>
</span>
The problem I'm having is that any generated anchors are not causing my click event to fire:
$("a.sr").click(function(){
alert("link clicked");
});
I noticed that if I hard code similar anchors within that div that the click event does fire. For some reason the ones that I programmatically add won't cause the click event to fire.
Does anyone see what I'm doing wrong here?
Thanks for any help,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 live() 而不是 click():
Use live() instead of click():
尝试使用
$("a.sr").live('click', function() {//...});
Try using
$("a.sr").live('click', function() {//...});