jQuery通过单击页面上的任意位置关闭DIV

jQuery通过单击页面上的任意位置关闭DIV

本文介绍了jQuery通过单击页面上的任意位置关闭DIV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击 email-signup-link 时,我想打开电子邮件注册。当然,我希望通过点击页面上的任何地方来关闭它。



我浏览过这个网站,有各种解决方案这个问题,但每一个我试过显示,然后立即隐藏我的div。



这是HTML:

 < a href =#id =email-signup-link>注册< / a> 
< div id =email-signup>
< div id =inner>
< h2>电子邮件通知< / h2>
< input class =type =textname =descriptionplaceholder =输入您的电子邮件地址id =description/>
< a href =#>注册< / a>
< / div>
< / div>

这是我的Javascript:



<$ p $点击(功能(){
e.stopPropagation();
});点击 $('#email-signup'
$(#email-signup-link)。click(function(){
e.preventDefault();
$('#email-signup')。show();
});
$(document).click(function(){
$('#email-signup')。hide();
});


解决方案

你实际上并没有定义 e ,所以你不能使用它。您还需要在其他点击处理程序中使用 stopPropagation

  $ ('#email-signup')。click(function(e){
e.stopPropagation();
});
$(#email-signup-link)。click(function(e){
e.preventDefault();
e.stopPropagation();
$(' #email-signup')。show();
});
$(document).click(function(){
$('#email-signup')。hide();
});

http://jsfiddle.net/Nczpb/


I would like to open email-signup when I click on email-signup-link. Then I would like to close it by clicking anywhere on the page except for the box itself, of course.

I have looked around on this site and there are various solutions for this problem but every one I've tried shows and then hides my div instantly. I must be doing something wrong.

This is the HTML:

<a href="#" id="email-signup-link">Sign Up</a>
<div id="email-signup">
    <div id="inner">
        <h2>E-mail Notifications</h2>
        <input class="" type="text" name="description" placeholder="Enter your e-mail address" id="description" />
        <a href="#">Sign Up</a>
    </div>
</div>

This is my Javascript:

$('#email-signup').click(function(){
    e.stopPropagation();
});
$("#email-signup-link").click(function() {
    e.preventDefault();
    $('#email-signup').show();
});
$(document).click(function() {
    $('#email-signup').hide();
});
解决方案

Two things. You don't actually have e defined, so you can't use it. And you need stopPropagation in your other click handler as well:

$('#email-signup').click(function(e){
    e.stopPropagation();
});
$("#email-signup-link").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $('#email-signup').show();
});
$(document).click(function() {
    $('#email-signup').hide();
});​

http://jsfiddle.net/Nczpb/

这篇关于jQuery通过单击页面上的任意位置关闭DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:18