为什么这个jQuery代码一行就无休止地循环
//$('."+triggerThisChild).trigger("click");这导致无穷无尽 圈
是未评论小提琴在这里
j查询代码:
$('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>
.showFancy0
上的单击事件冒泡到父a
,整个事情再次运行。
添加此代码以阻止它发生...
$(".showFancy0").on("click", function(e) {
e.stopPropagation();
});
工作小提琴
元素的子元素上触发的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 */);
}
});
您正在 onClick 函数内触发单击事件。因此,每当您单击触发该函数的元素时,它都会一遍又一遍地有效地调用同一个函数。