gpt4 book ai didi

javascript - 从一个选择器更新多个元素?

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

我想从同一选择器更新多个元素(具有不同的值)。执行此操作最简单的方法是什么?我已经尝试过

$(document).ready(function(){
var t=$('.test input');
t[0].val('Foo');
t[1].val('Bar');
});

使用此 HTML

<div class="test">
<input type="text">
<input type="text">
</div>

这里有一个实例 http://jsbin.com/afoda/6

但我收到一个错误:undefined t[0].val is not a function。访问这样的多个元素的正确方法是什么?

最佳答案

您可以使用 .eq(index) 获取 .val() ,像这样:

$(document).ready(function(){
var t=$('.test input');
t.eq(0).val('Foo');
t.eq(1).val('Bar');
});

You can test it here , .eq() 获取表示该索引处的元素的 jQuery 对象,而不是 DOM 元素。这种方法也有效(如果您坚持输入,那么它在 <select> 元素上的工作效果就不一样):

$(document).ready(function(){
var t=$('.test input');
t[0].value = 'Foo';
t[1].value = 'Bar';
});

You can test that here

关于javascript - 从一个选择器更新多个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3241666/

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