myFunc()绑定到文档滚动,因此它将被调用很多。我想将HTML选择存储在var中并将它们传递给函数。当我在下面运行我的示例时,我得到控制台错误Unable to get value of the property 'css': object is null or undefined
。
var a1 = $('#a1');
var a2 = $('#a2');
$(document).bind("scroll", function() {
setTimeout(myFunc, 1000, a1, a2);
}
function myFunc(a1, a2) {
a1.css('color', 'blue');
a2.css('font-weight', 'bold');
}
如何将存储在变量中的多个jQuery选择器传递给函数?
答案 0 :(得分:5)
$(document).bind("scroll", function() {
setTimeout(function() {
myFunc(a1, a2);
},1000);
}); // close );
function myFunc(a1, a2) {
a1.css('color', 'blue');
a2.css('font-weight', 'bold');
}
答案 1 :(得分:2)
尝试以下方法:
$(document).bind("scroll", function() {
setTimeout(function() {
myFunc(a1, a2);
}, 1000);
}); // and close properly your function
答案 2 :(得分:0)
您的a1
和a2
变量可能会在页面上存在#a1
和#a2
的元素之前设置(特别是如果它未包含在onload /中就绪处理程序和脚本在标题中)。我会这样设置,以确保滚动事件时存在#a1
和#a2
。
var a1 = undefined;
var a2 = undefined;
$(document).bind("scroll", function() {
if(typeof(a1) === "undefined") { a1 = $("#a1");} //will only reset a1 if undefined
if(typeof(a2) === "undefined") {a2 = $("#a2");}
setTimeout(function(){myFunc(a1,a2)}, 1000);
}); //don't forget your ')'
function myFunc(a1, a2) {
a1.css('color', 'blue');
a2.css('font-weight', 'bold');
}
答案 3 :(得分:0)
您还可以将元素存储在数组中:
<强> jsBin demo 强>
var a1 = ['#a1','#a2'];
$(document).bind("scroll", function() {
setTimeout(function() {
myFunc(a1);
}, 1000);
});
function myFunc(el) {
$(el[0]).css('color', 'blue');
$(el[1]).css('font-weight', 'bold');
}