开发者

How to implement jQuery's .not()?

开发者 https://www.devze.com 2023-01-07 04:47 出处:网络
I have code like: document.onmousedown = function(){ alert(\'test\'); } Now, except the element with ID \"box\", clicking should call this function, i.e. the equivalent of jQuery\'s .not() selector

I have code like:

document.onmousedown = function(){
    alert('test');
}

Now, except the element with ID "box", clicking should call this function, i.e. the equivalent of jQuery's .not() selector.

The jQuery code would be:

$(document).not('#box').mousedown(function(){
     alert('test');
});

How can I achieve the same thing without using jQuery?

Edit: I don't want jQuery code, but i want an action similar to the .not() selector of jQuery in Javascript.

Edit: I am making an addthis-like widget. It is a 10kb file which will show a popup when a text is selected. It will not use jQuery.

In my case, when a text is selected, a popup is shown. When the document is cli开发者_如何学JAVAcked somewhere other than the widget, the widget should disappear.


To do this properly, you need to check whether e.target || e.srcElement or any of its parents has id === 'box'.

For example: (with jQuery)

$(document).mousedown(function(e) {
    if ($(e.target).closest('#box').length)
        return;

    //Do things
});

Without jQuery:

function isBox(elem) {
    return elem != null && (elem.id === 'box' || isBox(elem.parentNode));
}
document.onmousedown = function(e) {
    e = e || window.event;
    if (isBox(e.target || e.srcElement))
        return;
    //Do things
};

Alternatively, you could handle the mousedown event for the box element and cancel bubbling.


Here's one way that should work:

document.onmousedown = function(e){
   var event = e || window.event;
   var element = event.target || event.srcElement;
   if (target.id !== "box") { alert("hi"); } 
}

or if you would like it to be reusable with different ids:

function myNot(id, callback) {
    return function (e) {
       var event = e || window.event;
       var element = event.target || event.srcElement;
       if (target.id !== id) { callback(); } 
    }
}

and to use it:

document.onmousedown = myNot("box", function () {
    alert("hi");
});


The cleanest way I can come up with for what you're trying to do is to set a document.onmousedown event and then halt event propagation on the box.onmousedown event. This avoids creating a large number of onmousedown events all over the document, and avoids having to recurse through the entire parent hierarchy of a node every time an event is triggered.

document.onmousedown = function() {
    alert("Foo!");
};
document.getElementById("box").onmousedown = function(e) {
    alert("Bar!");
    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;          
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消