简体   繁体   中英

How to remove conflict between click event and programmatically triggered click event

I am trying to remove ul element on click of body element and ignore if the click target is on the ul element itself otherwise click execute and ul get removed. Every thing works well but a programmatic click from another js removes ul after its execution which is a problem.The ul should be removed by the user interaction only. Please help me to solve this conflict.

<div class="search-input">
     <ul>
    <li><a href='#'>1</a></li>
    <li><a href='#'>2</a></li>
    </ul>
</div>

$(document).on('click','body', function(e) {
    if(!$(e.target).closest(".search-input").find('ul').length > 0) {
        $('.search-input ul').remove();
    }   
});

// programmatic click trigger $(hotspot).trigger("click", true);

The above programmatic click event execute the body click event which is not required.

Put this condition.

is_click  = true;
$(document).on('click','body', function(e) {
if(is_click){
    if(!$(e.target).closest(".search-input").find('ul').length > 0) {
        $('.search-input ul').remove();
    }

    if(!$(e.target).closest(".input-search").find('ul').length > 0) {
        $('.input-search ul').remove();
    } 
}  
});

and for programmatic click trigger

is_click  = false;
$(hotspot).trigger("click", true);
is_click  = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM