简体   繁体   English

.not()不起作用

[英].not() not working

I am making a login form that appears when you click a link. 我正在制作一个单击链接时出现的登录表单。 I then want the login form to disappear when I click on anything else, or the login link. 然后,当我单击其他任何内容或登录链接时,我希望登录表单消失。 However, when I attempt to use the jQuery .not() function, and also the :not() selector, it will still target all elements (it will not remove the elements specified from the selection). 但是,当我尝试使用jQuery .not()函数以及:not()选择器时,它仍将定位所有元素(不会从选择中删除指定的元素)。
If you want to take a look at the code, check out the jsFiddle . 如果您想看一下代码,请查看jsFiddle As you can see in the fiddle, when you click on the Login link, it appears, but then immediately fades away, because of the .click() statement, even though I am using the .not() function to remove that element, and the elements in the login form, from the selection. 正如您在小提琴中看到的那样,当您单击Login链接时,它会出现,但由于.click()语句而立即消失,即使我正在使用.not()函数删除该元素,以及从选择中选择的登录表单中的元素。 Clicking on the login form and the items inside it will also make it disappear, even though they are being removed with .not() . 单击登录表单及其中的项也将使其消失,即使使用.not()将其删除也是如此。

HTML: HTML:

<a id="login" href="javascript:void(0);" title="Login">Log in</a>
<div id="loginform" style="display:none;">
    <form action="login.php" method="POST">
        <input type="text" name="uname" id="uname" placeholder="Username" />
        <input type="password" name="pword" id="pword" placeholder="Password" />
        <input type="submit" id="loginbtn" value="Login" />
    </form>
</div>

Javascript: 使用Javascript:

$("#login").click(function() {
    $("#loginform").fadeToggle("slow");
    if ($("#login").text() == "Log in") {
        $("#login").text("Close");
        $("body, body *").not("#login, #loginform, #loginform *").bind("click", closeLoginForm);
    }
    else $("#login").text("Log in");
});
function closeLoginForm() {
    $("#loginform").fadeOut("slow");
    $("#login").text("Log in");
    $("*").unbind("click", closeLoginForm);
}

Your problem is event bubbling, the click event bubles up the dom and hits an element you didn't exclude with your not() call. 您的问题是事件冒泡,单击事件使dom冒泡,并击中了not()调用未排除的元素。 instead use the event handler to see source of the click an cancel it there. 而是使用事件处理程序查看点击来源,然后在此处取消它。

if ($(e.target).is("#login, #loginform, #loginform *")) return;

http://jsfiddle.net/ZgYcV/2/ http://jsfiddle.net/ZgYcV/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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