简体   繁体   English

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

[英]Updating multiple elements from one selector?

I would like to update multiple elements(with different values) from the same selector. 我想从同一个选择器更新多个元素(具有不同的值)。 What would be the easiest way to go about doing this? 这样做最简单的方法是什么? I have tried 我努力了

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

with this HTML 用这个HTML

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

A live example is here http://jsbin.com/afoda/6 一个实时示例在这里http://jsbin.com/afoda/6

I get an error though for undefined t[0].val is not a function . 尽管undefined t[0].val is not a function但出现错误。 What is the proper way to access multiple elements like this? 访问这样的多个元素的正确方法是什么?

You can use .eq(index) to get .val() , like this: 您可以使用.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() get the jQuery object representing the element at that index, rather than the DOM element. 您可以在此处进行测试.eq()获得表示该索引处元素而不是DOM元素的jQuery对象。 This approach also works (if you're sticking to inputs, it wouldn't work the same for example on a <select> element): 这种方法也可以工作(如果您坚持使用输入,例如在<select>元素上将无法正常工作):

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

You can test that here 你可以在这里测试

When you are accessing the elements in a jQuery object by index, you don't get a new jQuery object with each element, you just get the element. 当您通过索引访问jQuery对象中的元素时,不会随每个元素获得一个新的jQuery对象,而只是获取该元素。 If you want to use the val method you need to create a jQuery object for each element: 如果要使用val方法,则需要为每个元素创建一个jQuery对象:

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

Another way is to loop through the elements and get values from an array: 另一种方法是遍历元素并从数组中获取值:

$(document).ready(function(){
  var values = ['Foo', 'Bar'];
  $('.class input').each(function(i){
    $(this).val(values[i]);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM