jQuery trigger click gives “too much recursion”

前端 未结 2 1220
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 00:05

I\'m tryin\' to make the article\'s link clickable on the whole article space.

First, I did the hover thing, changing color on mouseover and so on... then on click i

2条回答
  •  -上瘾入骨i
    2021-02-08 00:31

    The problematic bit of your code is this:

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

    This says "every time any click event is received on this element, trigger a click on the descendant element". However, event bubbling means that the event triggered in this function is then handled again by this event handler, ad infinitum. The best way to stop this is, I think, to see if the event originated on the div.btn a element. You could use is and event.target for this:

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

    This says "if the click originated on any element apart from a div.btn a, trigger a click event on div.btn a. This means that events caused by the trigger call will not be handled by this function. This is superior to checking event.target == this (as Andy's answer has it) because it can cope with other elements existing within the div.boxContent.

提交回复
热议问题