jQuery触发器点击无限循环

时间:2013-09-10 15:29:39

标签: jquery

为什么这个jQuery代码会在行

之后无休止地循环
  

// $('' + triggerThisChild).trigger("单击&#34); //这会导致无穷无尽   环

已取消注释FIDDLE is here

jQuery代码:

$('a.touchNav').on('click touchend', function (e) {
    var fancy = this.className.indexOf('fancy') != -1;
    var target = $(this).attr('target') == '_blank' ? true : false;
    if (fancy) {
        var triggerThisChild = $(this).children('span').attr('class');
        alert(triggerThisChild);
        e.stopPropagation();
        //$('.'+triggerThisChild).trigger("click"); // this causes endless loop
        //return false;
    } else if (target) {
        window.open(this.href,target);
        return false;
    } else {
       window.location = this.href;
       return false;
    }
});

$(".showFancyBox").fancybox({
    "width" : "75%",
    "height" : 800,
    "transitionIn" : "none",
    "transitionOut" : "none",
    "type" : "iframe",
    'href' : "http://www.google.com"
});

HTML:

<li>
<a class="touchNav" href="http://www.google.com" target="_blank">
    Nav Point 1
</a>
</li>
<li>
<a class="touchNav" href="http://www.stackoverflow.com" target="_blank">
    Nav Point 2
</a>
</li>
<li>
<a class="fancy touchNav" href="#">
    <span class="showFancy0" style="display:none;"></span>
    Nav Point 3
</a>
</li>

3 个答案:

答案 0 :(得分:7)

.showFancy0上的点击事件冒泡到父a,整个事情再次运行。

添加此代码以阻止它发生......

$(".showFancy0").on("click", function(e) {
    e.stopPropagation();
});

Working fiddle

答案 1 :(得分:1)

您正在onClick函数中触发click事件。因此,每次单击触发该函数的元素时,它都会反复调用相同的函数。

答案 2 :(得分:1)

您在元素的子元素上触发的click事件将冒泡,并再次触发您在元素本身上放置的click回调。

在您显示的代码中,没有任何内容可以阻止点击事件从'.'+triggerThisChild元素冒出来。

我不会触发click事件,而是将相关代码放在一个单独的函数中,并从两个处理程序中调用该函数。例如:

而不是:

$('.showFancy0').on('click', function(e) {
       //code to display fancybox
});

$('a.touchNav').on('click touchend', function(e){
     if (conditions) {
        $('.showFancy0').trigger('click');
     }
});

写道:

function showFancyBox(/* any arguments you need */) {
   //code to show fancybox
}

$('.showFancy0').on('click', function(e) {
       showFancyBox(/* get the arguments and pass them */);
});

$('a.touchNav').on('click touchend', function(e) {
    if (conditions) {
       showFancyBox(/* get the arguments and pass them */);
    }
});