jquery-selectors - jquery.live 未调用

标签 jquery-selectors jquery

假设在 HTML 文档上我有一堆链接,如下所示:

<a href="#path" class="the_link_1">Click here 1</a>
<a href="#path" class="the_link_2">Click here 2</a>
<a href="#path" class="the_link_3">Click here 3</a>
<a href="#path" class="the_link_4">Click here 4</a>
etc...

我有这样的jquery代码:

$("a[class^=the_link_]").each(function(){

    $(this).live("click", function(){

        alert($(this).html());

    });

});

为什么当我使用 $(this).click(function(){ ... }); 时它有效,但当我使用 $(this) 时它不起作用。 live("点击", function(){ ... }); ?

谢谢

最佳答案

.live很奇怪,并且只适用于选择器。我的意思是$('div').live作品和$(div).live没有。

此外,您不需要 .each将单击处理程序应用于多个元素时。 $("a[class^='the_link_']").click按预期工作。

您的代码应该是:

$("a[class^='the_link_']").live("click", function(){
    alert($(this).html());
});

更新:从 jQuery 1.7 开始, .live() 已弃用,请使用 .on() 相反。

$(document).on('click', "a[class^='the_link_']", function(){
    alert($(this).html());
});

注意:如果所有 <a>标签位于一个容器中,您可以替换 $(document)使用该容器(只要它始终位于 DOM 中)。

编辑:你真的需要使用 .live这里?它用于将事件绑定(bind)到元素,即使它们稍后添加到 DOM 中也是如此。如果您从不添加更多 <a>通过 JavaScript 标记,然后执行以下操作:

$("a[class^='the_link_']").click(function(){
    alert($(this).html());
});

关于jquery-selectors - jquery.live 未调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9417932/

相关文章:

javascript - jquery,触发链接点击与另一个点击问题?

jquery 在类中选择元素

javascript - jQuery 中的选择器以一种不直观的方式工作

javascript - 基于计时器 jQuery 循环悬停状态

javascript - 几秒钟后 Jquery animation() 响应非常缓慢

javascript - 将元素放入卡中的问题

jQuery - 通过元素 id 设置选择索引

jquery - 是否有任何理由使用选择器 '*.class' 而不是 '.class' ?

jQuery 选择器 : exclusive OR

javascript - JQuery 和操作通过对象标签加载的 SVG?