jQuery触发器点击给出"太多的递归"

Tho*_*mas 11 javascript jquery events triggers event-bubbling

我试着让文章的链接在整个文章空间中都可以点击.

首先,我做了悬停的事情,在鼠标悬停时改变颜色等等......然后点击它应该触发链接,但这会产生"过多的递归".

我认为这是一个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');
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

lon*_*day 33

你的代码中有问题的一点是这样的:

$("div.boxContent") /* miss the each function */
.click(function() {
    $(this).find("div.btn a").trigger('click');
});
Run Code Online (Sandbox Code Playgroud)

这表示"每次在此元素上收到任何点击事件时,都会触发对后代元素的点击".但是,事件冒泡意味着此函数触发的事件随后将由此事件处理程序再次处理,无限制.我认为,阻止这种情况的最佳方法是查看事件是否源自div.btn a元素.你可以使用isevent.target为此:

$("div.boxContent") /* miss the each function */
.click(function(event) {
    if (!$(event.target).is('div.btn a')) {
        $(this).find("div.btn a").trigger('click');
    }
});
Run Code Online (Sandbox Code Playgroud)

这说"如果点击源于除a之外的任何元素div.btn a,则触发点击事件div.btn a.这意味着trigger该函数不会处理由该调用引起的事件.这比检查更好event.target == this(因为Andy的答案有),因为它可以应付其中存在的其他元素div.boxContent.