Javascript jQuery:是否可以将DOM元素分配给变量以供以后使用?
我正在从事一个使用jQuery的项目,我对jQuery工具更为熟悉 我先从我的代码开始Javascript jQuery:是否可以将DOM元素分配给变量以供以后使用?,javascript,jquery,Javascript,Jquery,我正在从事一个使用jQuery的项目,我对jQuery工具更为熟悉 我先从我的代码开始 var customNamespace = { status: 'closed', popup: $('#popup'), showPopup: function() { // ... } } $(document).ready(function(){ console.log($('#popup')); console.log(custo
var customNamespace = {
status: 'closed',
popup: $('#popup'),
showPopup: function() {
// ...
}
}
$(document).ready(function(){
console.log($('#popup'));
console.log(customNamespace.popup);
console.log($(customNamespace.popup));
$('#popup').fadeIn('slow');
(customNamespace.popup).fadeIn('slow');
$(customNamespace.popup).fadeIn('slow');
});
我的目标是不让jQuery在每次我想使用#popup div时都遍历DOM,所以我想将它保存到一个变量中,以便在整个脚本中使用它
当页面加载时,控制台会像我预期的那样打印出3次对象,因此我假设对于每个方法,fadeIn都会正常工作。但事实并非如此
$('#popup').fadeIn('slow');
实际上,它会在div中消失
即使我删除了名称空间散列,并将对象保存到一个全局变量中,然后执行
var globalVariable = $('#popup');
.
.
.
globalVariable.fadeIn('slow');
也不工作,因为我认为它会。jQuery可以做我想做的事情吗?当然可以。实际上,提高性能是一件好事。您在哪里分配全局变量 如果它在document.ready声明之外,那么您可能正在为它分配一些尚未加载的内容 试试这个:
$(document).ready(function(){
var customNamespace = {
status: 'closed',
popup: $('#popup'),
showPopup: function() {
// ...
}
}
console.log($('#popup'));
console.log(customNamespace.popup);
console.log($(customNamespace.popup));
$('#popup').fadeIn('slow');
(customNamespace.popup).fadeIn('slow');
$(customNamespace.popup).fadeIn('slow');
});
尝试输出.length
时会发生什么情况
console.log($('#popup').length);
console.log(customNamespace.popup.length);
console.log($(customNamespace.popup.length));
在运行选择器并将其分配给变量之前,您需要注意DOM是否已实际加载,否则您可以在变量中存储对DOM元素的引用,而不会出现任何问题
var globalVariable;
$(document).ready(function(){
globalVariable = $('#popup');
console.log($('#popup'));
console.log(globalVariable);
$('#popup').fadeIn('slow');
globalVariable.fadeIn('slow');
});
从
$()
得到的所有东西都将始终是一个对象。您的问题是,当分配customNamespace
并执行代码时,DOM元素#popup
还不存在,因此,在该示例中,您将得到一个长度为零的对象
要检查是否在jQuery中找到对象,不检查结果是否为null,而是检查其长度
要确保在执行代码时DOM节点存在,请将其推迟到DOMReady:
$(document).ready(function() {
...
});
使用数据方法并避免将数据存储在DOM中。一些开发人员有将数据存储在HTML属性(如fx)中的习惯:
$('selector').attr('alt', 'data being stored');
//稍后,可以使用以下方法检索数据:
$('selector').attr('alt')
HTML属性并不是用来存储这样的数据,而“alt”作为参数名也没有实际意义。在大多数情况下,正确的选择是在jQuery中使用数据方法。它允许您将数据与页面上的元素相关联
$('selector').data('paramtername', 'data being stored');
//然后稍后使用
$('selector')。数据('parameterName')
这种方法允许您使用有意义的名称存储数据,而且更灵活,因为您可以在页面上的任何元素上存储任意数量的数据。有关data()和removeData()的更多信息,请参见这里的一个经典用法是保存输入字段的默认值,因为您希望在焦点上清除它
<form id="testform">
<input type="text" class="clear" value="Always cleared" />
<input type="text" class="clear once" value="Cleared only once" />
<input type="text" value="Normal text" />
</form>
$(function() {
//Go through every input field with clear class using each function
//(NB! "clear once" is two classes clear and once)
$('#testform input.clear').each(function(){
//use the data function to save the data
$(this).data( "txt", $.trim($(this).val()) );
}).focus(function(){
// On focus test for default saved value and if not the same clear it
if ( $.trim($(this).val()) === $(this).data("txt") ) {
$(this).val("");
}
}).blur(function(){
// Use blur event to reset default value in field that have class clear
// but ignore if class once is present
if ( $.trim($(this).val()) === "" && !$(this).hasClass("once") ) {
//Restore saved data
$(this).val( $(this).data("txt") );
}
});
});
$(函数(){
//使用每个函数使用clear类遍历每个输入字段
//(注意!“清除一次”是两类清除和一次清除)
$('#testform input.clear')。每个(函数(){
//使用数据功能保存数据
$(this.data(“txt”,$.trim($(this.val()));
}).focus(函数(){
//对焦测试默认保存值,如果不相同,则清除该值
if($.trim($(this.val())====$(this.data(“txt”)){
$(此).val(“”);
}
}).blur(函数(){
//使用模糊事件重置具有清除类的字段中的默认值
//但是,如果类曾经存在,则忽略它
if($.trim($(this.val())===“”&&&&!$(this.hasClass(“一次”)){
//恢复保存的数据
$(this.val($(this.data(“txt”));
}
});
});
这里演示:我喜欢用类似的方式构造我的脚本。对我来说,它将我所有的页面控件保持在一起。 它还允许我更轻松地维护每个页面的脚本
/* CONTROLS GLOBAL */
var Controls;
var Class = {
create: function () {
return function () {
this.initialize.apply(this, arguments);
}
}
}
//Set up page control objects
PageControls = Class.create();
PageControls.prototype = {
initialize: function () {
//Use jquery to initialize our controls,
//one should probably use more appropriate names other than ctrl1, ctrl2 ..
//but for demo purposes ...
this.ctrl1 = $($("#Control1"));
this.ctrl2 = $($("#Control2"));
this.ctrl3 = $($("#Control3"));
}
}
一旦准备好
$(document).ready(function () {
/* Initialize our global page controls */
Controls = new PageControls();
//Now we can use our controls
Controls.ctrl1.val("Text for control 1");
Controls.ctrl2.val("Text for control 2");
Controls.ctrl3.val("Text for control 3");
});
非常感谢。我花了一上午的时间忘记了DOM在试图访问其元素时甚至没有加载。这让我发疯,因为我认为代码应该按原样工作。