0

I'm just beginning to learn jQuery, basically I want to recreate "click outside element" event. A similar question has been asked here:

How do I detect a click outside an element?

But this doesn't work for multiple elements. I want to have multiple drop-down boxes on my page and I only want one to be visible at a time. If a user clicks outside the box or the same drop-down link, the opened box has to close (and a new one has to open if the user clicks a different drop-down link). I have my code here:

http://jsfiddle.net/JvCUd/2/

I'm trying to store the jQuery specifier (or id) of the currently opened box in a global variable:

jsOpenedWnd = "";
$(document).ready(function()  {
...
});

The function that I want to use is this :

$.fn.toggleWnd = function() {       
    if ( jsOpenedWnd != this ) {
        $(this).toggle();
        $(jsOpenedWnd).toggle();
        jsOpenedWnd = this;
    }
    else {   
        $(this).toggle();
        jsOpenedWnd = "";
    }
}

But it's not working properly. I'm aware that this may be a wrong solution to this problem, but just for the learning purposes I would like to know how to make this work.

EDIT: Finally worked it out. Turns out the answer was all along in the question that I linked, I had to use event.stopPropagation();

Here is the updated code (only one window is active at a time): http://jsfiddle.net/HwE2N/

4

1 回答 1

1

您可以使用 .is() 检查它们,因为this它是一个 jQuery 包装器并且jsOpenedWnd是一个选择器,因此您无法使用相等性来比较它们

$.fn.toggleWnd = function() {       
    if ( !this.is(jsOpenedWnd)) {
        $(this).toggle();
        $(jsOpenedWnd).toggle();
        jsOpenedWnd = this;
    }
    else {   
        $(this).toggle();
        jsOpenedWnd = "";
    }
}

演示:小提琴

于 2013-08-26T16:52:15.300 回答