jQuery $('a')没有按预期工作

时间:2014-01-17 10:47:46

标签: jquery jquery-selectors

这可能相当简单,但我真的尝试过我能想到的每一个组合(以及谷歌)如何解决这个问题,但根本没有任何效果。

我有这个块:

$(document).ready(function(){
    $('a').not("div.thatguy a, div#thisguy a").click(function(event) {
        // do things
    });
});

奇怪的是它没有正确选择链接(?!)。

我想要的是它适用于除div.thatguy和div#thisguy内的每个链接。

现在正在发生的是它适用于这些链接:

  • domain.com/about /
  • domain.com/that /
  • domain.com
  • domain.com/example /

但它不想使用这些链接:

  • domain.com/2010/check /
  • domain.com/2009/post /
  • domain.com/2012/thing /

它也忽略了我想要忽略的链接。

帮助?

编辑:我刚刚意识到可能是其他链接无效的原因。第一批链接(工作)在一段时间内第二批链接(不起作用)位于通过AJAX链接加载和替换的链接中。是否有可能jQuery不适用于那些?

编辑2 :这似乎有效。我没有意识到AJAX内容会影响脚本。抱歉! $('a').not("div.insertedimg a, div#thisguy").on('click', function(event) {

2 个答案:

答案 0 :(得分:2)

试试这个:

$(document).ready(function(){
    $('a').not("div.thatguy a").not("div#thisguy a").click(function(event) {
        // do things
    });
});

或者,

$(document).ready(function(){
    $('a:not("div.thatguy a"):not("div#thisguy a")').click(function(event) {
        // do things
    });
});

我正在接受@Salman A updated demo |的jsfiddle updated demo2正在运作。


您需要使用event delegation

示例:

// attach a directly bound event
$( "#list a" ).on( "click", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});

// attach a delegated event
$( "#list" ).on( "click", "a", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});

答案 1 :(得分:1)

是的,您需要使用事件委派

$(document).ready(function(){
    $(document).on('click', 'a:not(div.thatguy a, #thisguy a)', function(event) {
        // do things
    });
});
相关问题