jQuery trigger click gives “too much recursion”

前端 未结 2 1219
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  • 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.

    0 讨论(0)
  • 2021-02-08 00:47

    A cleaner way to solve this is to take the the element you are triggering the click on to and put it outside of the triggered element:

    So if you have this:

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

    By moving the "div.btn a" tag outside of the "boxContent" div. You avoid the recursion loop all together.

    0 讨论(0)
提交回复
热议问题