鉴于下面的jQuery下拉插件。有没有办法添加一个方法,允许在'hideMenu'的下拉菜单之外使用单独的函数?由于在全局可访问的插件中制作一个方法?
例如,如果我申请的插件一个div像这样的ID:
$('#settings.dropdown').dropDownMenu();
我怎么能然后调用从插件以外关闭dropDownMenuW¯¯hideMenu?谢谢
jQuery.fn.dropDownMenu = function() {
// Apply the Dropdown
return this.each(function() {
var dropdown = $(this),
menu = dropdown.next('div.dropdown-menu'),
parent = dropdown.parent();
// For keeping track of what's "open"
var activeClass = 'dropdown-active',
showingDropdown = false,
showingMenu,
showingParent,
opening;
// Dropdown Click to Open
dropdown.click(function(e) {
opening = true; // Track opening so that the body click doesn't close. This allows other js views to bind to the click
e.preventDefault();
if (showingDropdown) {
dropdown.removeClass(activeClass);
parent.removeClass(activeClass);
showingMenu.hide();
showingDropdown = false;
} else {
showingDropdown = true;
showingMenu = menu;
showingParent = parent;
menu.show();
dropdown.addClass(activeClass);
parent.addClass(activeClass);
}
});
// When you click anywhere on the page, we detect if we need to blur the Dropdown Menu
$('body').click(function(e) {
if (!opening && showingParent) {
var parentElement = showingParent[0];
if (!$.contains(parentElement, e.target) || !parentElement == e.target) {
hideMenu();
}
}
opening = false;
});
// hides the current menu
var hideMenu = function() {
if(showingDropdown) {
showingDropdown = false;
dropdown.removeClass(activeClass);
parent.removeClass(activeClass);
showingMenu.hide();
}
};
});
};
为什么用括号标记为这个? (即不是'window.hideMenu') – Ryan
我想你可以这样做,因为这只是一个意见问题。我更喜欢使用括号表示法,因为对我而言,第一眼看到自己在做什么更容易。 –
谢谢,介意给它一个窗口对象做什么?另外,我将如何调用hideMenu方法? – AnApprentice