此代码通过 jQuery 加载基于复选框单击事件的页面。
function product_analysis(address, box) {
if (box.checked) {
$('#product_' + box.alt).load(address);
} else {
$('#product_' + box.alt).load('http://www.divethegap.com/update/blank2.html');
}
document.getElementById('product_quantity_PRI_' + box.alt).value = box.value;
};
onclick 事件如下所示 onclick="product_analysis('http://www.samedomain.blahblahblah', this)
我需要的是,对于页面加载时已勾选的所有复选框,将此功能应用于所有复选框。我对 javaScript 有相当的信心,但当涉及到对象和数组时,我就迷失了。
非常感谢,
最佳答案
您可以使用此代码查找当前选中的所有复选框:
$(':checkbox:checked')
如果您想对所有这些进行操作,可以使用 each
函数,如下所示:
$(':checkbox:checked').each(function() {
// alerts the checkbox for example
// "this" referes to the checkbox, one after the other
alert(this);
})
或者执行您要求的操作(“对于页面加载时已勾选的所有复选框,以将此功能应用于所有复选框”):
$(':checkbox:checked').each(function() {
product_analysis("someaddress", this);
})
编辑:解决第二个问题(不是原始问题的一部分,而是下面的评论):
我假设您的标记中有这样的字段。当然,使用一些有意义的 ID,而不是我的愚蠢示例。
<input type="checkbox" id="foo" />
<input type="checkbox" id="bar" />
<input type="checkbox" id="baz" />
然后您将在 JS 中添加以下内容:
var addresses = {
foo: 'some_address',
bar: 'some_other_address',
baz: 'yet_another_one'
};
$(':checkbox:checked').each(function() {
product_analysis(addresses[this.id], this);
})
这将使用与复选框 ID 对应的地址调用 Product_analysis。
编辑(再次):
实际上有一种方法可以将元数据直接添加到我不知道的 html 标签中。您可以向标记添加前缀为“data-”的属性,如下所示:
<input type="checkbox" data-address="someaddress" data-foo="something else" data-bar="more data!" />
您可以在John Resigs blog上阅读更多相关信息。 .
关于javascript - 如何将其转换为影响所有值的全局 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4376510/