将JQuery选择器分配给变量一次
我有一个JQuery插件函数,我想从iframe中分配一次选择器,然后在整个插件中使用它们 在下面的基本示例中,如果我在插件中有一个函数,除非我在函数中显式地设置它,否则$modal选择器将不起作用 有没有什么方法可以做到这一点,这样我就可以将选择器只分配给一个变量一次,并在整个插件函数中访问它将JQuery选择器分配给变量一次,jquery,Jquery,我有一个JQuery插件函数,我想从iframe中分配一次选择器,然后在整个插件中使用它们 在下面的基本示例中,如果我在插件中有一个函数,除非我在函数中显式地设置它,否则$modal选择器将不起作用 有没有什么方法可以做到这一点,这样我就可以将选择器只分配给一个变量一次,并在整个插件函数中访问它 jQuery.customPlugin = function() { var $modal = $('#modal', frames['admin-bar'].document);
jQuery.customPlugin = function() {
var $modal = $('#modal', frames['admin-bar'].document);
$('#hide-modal').click(function(){
hide_modal();
});
// doesn't work - but I want it to somehow
function hide_modal(){
$modal.hide();
}
// works, but requires lots of re-querying if I have lots of selectors/functions
function hide_modal(){
var $modal = $('#modal', frames['admin-bar'].document);
$modal.hide();
}
});
jQuery选择器在您实例化它们时查询DOM。换句话说,如果执行var$foo=$'.bar',然后将带有类bar的新元素添加到页面中,$foo变量将不包含它。jQuery就是这样工作的 您可以编写一个方法get$Modal,它在每次运行时都会重新查询。例如:
function get$Modal() {
return $('#modal', frames['admin-bar'].document);
}
// Should work
function hide_modal(){
get$Modal().hide();
}
或者,您也可以在创建模态时注册它们,避免重新查询。比如:
var $modals = $('.modal');// start with any existing modals
function createModal() {
var $modal = generateModal();
modals.add($modal); // add any newly created modals
}
// Should work
function hide_modal(){
$modals.hide();
}
如果您有一个创建所有模态的公共位置,那么这将非常有用。如果在许多不同的地方创建模态,则可能需要使用自定义事件来组织:
var $modals = $('.modal');// start with any existing modals
$(document.body).on('newModal', function(e, $newModal) {
$modals.add($newModal);
})
function createModalPlace1() {
var $modal = generateModal();
$(document.body).trigger('newModal', $modal)
}
function createModalPlace2() {
var $modal = generateModalSomeOtherWay();
$(document.body).trigger('newModal', $modal)
}
function createModalPlace3() { // etc.
您可能还想了解下划线.js——它为这些类型的问题提供了很好的解决方案。虽然我喜欢下划线,并且会向任何JS开发人员推荐这个库,但我不认为它能帮助解决这个问题。下划线绑定、迭代器方法等中的绝妙技巧都不能帮助jQuery选择器避免过时。