我有一个JQuery插件函数,我只想从iframe中分配一次选择器,然后在整个插件中使用它们。
在下面的基本示例中,如果我在插件中有一个函数,除非我在函数中显式地设置它,否则它不会对$modal选择器起作用。
有没有办法做到这一点,这样我就可以将选择器赋给一个变量一次,并让它在整个插件函数中都可以访问?
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();
}
});发布于 2012-06-28 03:32:48
jQuery选择器在实例化DOM时查询它们。换句话说,如果您执行了var $foo = $('.bar')操作,然后向页面添加了一个类为“var $foo = $('.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.https://stackoverflow.com/questions/11233581
复制相似问题