jQuery を使用して、ユーザーが DIV の外側をクリックしたときに DIV を非表示にする 質問する

jQuery を使用して、ユーザーが DIV の外側をクリックしたときに DIV を非表示にする 質問する

私は次のコードを使用しています:

$('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});

そしてこのHTML :

<div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

問題は、内部にリンクがありdiv、クリックしても機能しなくなることです。

ベストアンサー1

同じ問題を抱えていたのですが、この簡単な解決策を思いつきました。再帰的にも動作します:

$(document).mouseup(function(e) 
{
    var container = $("YOUR CONTAINER SELECTOR");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

おすすめ記事