我试着让文章的链接在整篇文章空间中可点击。
首先,我做了悬停的事情,在鼠标悬停时改变颜色等等......然后点击它会触发链接,但这会产生“过多的递归”。
我认为这是一个event bubbling
问题。我尝试使用event.cancelBubble = true;
或stopPropagation()
但没有运气。更糟糕的运气!
人
$("div.boxContent").each(function() {
if ($(this).find(".btn").length) {
var $fade = $(this).find("div.btn a > span.hover");
var $title = $(this).find("h1, h2, h3, h4, h5");
var $span = $(this).find("span").not("span.hover");
var $text = $(this).find("p");
var titleColor = $title.css('color');
var spanColor = $span.css('color');
$(this).css({'cursor':'pointer'}).bind({
mouseenter:function() {
$text.stop().animate({color:linkHover},textAnim);
$title.stop().animate({color:linkHover},textAnim);
$span.stop().animate({color:linkHover},textAnim);
$fade.stop(true,true).fadeIn(textAnim);
}, mouseleave:function() {
$text.stop().animate({color:linkColor},textAnim);
$title.stop().animate({color:titleColor},textAnim);
$span.stop().animate({color:spanColor},textAnim);
$fade.stop(true,true).fadeOut(textAnim);
}, focusin:function() {
$text.stop().animate({color:linkHover},textAnim);
$title.stop().animate({color:linkHover},textAnim);
$span.stop().animate({color:linkHover},textAnim);
$fade.stop(true,true).fadeIn(textAnim);
}, focusout:function() {
$text.stop().animate({color:linkColor},textAnim);
$title.stop().animate({color:titleColor},textAnim);
$span.stop().animate({color:spanColor},textAnim);
$fade.stop(true,true).fadeOut(textAnim);
}
}).click(function() {
$(this).find("div.btn a").trigger('click');
});
}
});
答案 0 :(得分:31)
代码中有问题的一点是:
$("div.boxContent") /* miss the each function */
.click(function() {
$(this).find("div.btn a").trigger('click');
});
这表示“每次在此元素上收到任何点击事件时,都会触发对后代元素的点击”。但是,事件冒泡意味着此事件中触发的事件将由此事件处理程序 ad infinitum 再次处理。我认为,阻止这种情况的最佳方法是查看事件是否源自div.btn a
元素。您可以使用is
和event.target
:
$("div.boxContent") /* miss the each function */
.click(function(event) {
if (!$(event.target).is('div.btn a')) {
$(this).find("div.btn a").trigger('click');
}
});
这表示“如果点击源自div.btn a
以外的任何元素,则触发div.btn a
上的点击事件。这意味着trigger
调用导致的事件将无法处理通过此功能。这比检查event.target == this
(Andy's answer has it)要好,因为它可以处理div.boxContent
中存在的其他元素。
答案 1 :(得分:-1)
解决此问题的一种更简洁的方法是将触发点击的元素取出并将其放在触发元素之外:
所以如果你有这个:
<div class="boxContent">
<div class="btn">
<a href="#">link</a> <!-- move this line... -->
</div>
</div>
<!-- ... to here. -->
<script>
$("div.boxContent") /* miss the each function */
.click(function() {
$(this).find("div.btn a").trigger('click');
});
</script>
将“div.btn”标记移到“boxContent”div之外。你可以一起避免递归循环。