6

このjQueryコードは、行が終わるとすぐに無限にループするのはなぜですか

//$('.'+triggerThisChild).trigger("クリック"); // これにより無限ループが発生します

FIDDLEはこちら

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>
4

3 に答える 3

2

要素のclick子に対してトリガーするイベントはバブルアップclickし、要素自体に配置したコールバックを再度トリガーします。

'.'+triggerThisChildあなたが示すコードでは、クリックイベントが要素から発生するのを止めるものは何もありません。

クリック イベントをトリガーするのではなく、関連するコードを別の関数に入れ、両方のハンドラーからその関数を呼び出します。例:

それよりも :

$('.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 */);
    }
});
于 2013-09-10T15:34:10.140 に答える
1

onClick 関数内でクリック イベントをトリガーしています。したがって、関数をトリガーする要素をクリックするたびに、事実上、同じ関数が何度も呼び出されます。

于 2013-09-10T15:33:33.717 に答える