假设我有一个这样的文本框选择;
var arrayoftextboxes = $('.textbox1, .textbox2, .textbox3');
有没有一种方法可以比这更简单地调用每个函数? 只需调用一次。
arrayoftextboxes.each(function(i){foo(arrayoftextboxes[i]);});
我试过了
arrayoftextboxes.load(function(){foo(this)});
和
arrayoftextboxes.bind(function(){foo(this)});
但函数似乎没有被调用。
最佳答案
你可以这样做:
$('.textbox1, .textbox2, .textbox3').each(function() { foo(this); });
.each()
call 创建一个闭包,其中 this
引用您当前所在的 DOM 元素,但最好将您所拥有的内容写为 jQuery plugin 。或者,如果您只是在 foo
中使用 this
(而不是 DOM 元素作为参数),您可以将其缩短为:
$('.textbox1, .textbox2, .textbox3').each(foo);
Here's a demonstration of that method
另外,请确保您在 document.ready
上运行它,如下所示:
$(function() {
$('.textbox1, .textbox2, .textbox3').each(foo);
});
否则,可能无法找到 DOM 元素,从而使该选择器返回一个空数组(因此无法运行任何内容)。
关于javascript - 使用 Jquery,仅在选择时调用函数一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3052392/