gpt4 book ai didi

javascript - 循环遍历 jQuery 对象

转载 作者:行者123 更新时间:2023-11-28 11:55:01 25 4
gpt4 key购买 nike

我有一个包含 jQuery 对象的关联数组,我想对其进行循环以在每个对象上设置一个值。

我对 JavaScript/jQuery 比较陌生,但这是我尝试过的,但没有任何运气:

var inputs = [
{ key: "firstName", val: $("#signup input[name=firstName]") },
{ key: "lastName", val: $("#signup input[name=lastName]") },
{ key: "email", val: $("#signup input[name=email]") },
{ key: "confirmationEmail", val: $("#signup input[name=confirmationEmail]") },
{ key: "password", val: $("#signup input[name=password]") },
{ key: "terms", val: $("#signup input[name=terms]") }
];

inputs.each(function() {
$(this).val("test");
});

最佳答案

在较新的浏览器中,您不需要 jQuery:

inputs.forEach(function(input) {
console.log("key is " + input.key);
input.val.val("test");
});

.forEach()方法是内置的。如果必须使用jQuery .s .each()` 它看起来像这样:

$.each(inputs, function(index, input) {
console.log("key is " + input.key);
input.val.val("test");
});

请注意 jQuery $.each()使用元素的索引作为第一个参数,元素本身作为第二个参数来调用回调函数。原生.forEach()以相反的顺序传递它们。

最后作为注释,您可以设置所有<input> “signup”元素下的值

$("#signup input").val("test");

关于javascript - 循环遍历 jQuery 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25608769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com