简体   繁体   English

使用jQuery获取输入值数组

[英]Getting an array of input values with Jquery

I am selecting all input elements with class "img-title" in order to get an array with the current value of these inputs: 我选择所有带有“ img-title”类的输入元素,以获得具有这些输入的当前值的数组:

var values = []
for (let element of $(".img-title")){ 
   values.push( element.val() ) }

But this doesn't work, because the elements of $(".img-title") are not the references to the inputs as I expected, but the html code, so val() rises an error. 但这是行不通的,因为$(".img-title")元素不是我所期望的对输入的引用,而是html代码,因此val()会引发错误。 Is there a simple way to get the array with the current values of the inputs with class "img-title" ? 有没有一种简单的方法来获取具有“ img-title”类的输入的当前值的数组?

When you use for..of over a jQuery collection, the items you get back are the elements themselves, not a jQuery collection which contains that element. 当在jQuery集合上使用for..of ,返回的项是元素本身,而不是包含该元素的jQuery集合。 Either turn the element into a jQuery collection first before calling .val() on it: 在调用.val()之前, .val()其转换为jQuery集合:

const values = []
for (const element of $(".img-title")){ 
  values.push( $(element).val() )
}

Or, access the property on the native element just with .value : 或者,仅使用.value访问本机元素上的属性:

const values = []
for (const element of $(".img-title")){ 
  values.push( element.value )
}

Or, consider using .map instead: 或者,考虑改用.map

const values = $(".img-title")
  .map(function() {
    return $(this).val();
  })
  .get();

(make sure to use .get() at the end, to get the array, rather than the jQuery collection) (确保最后使用.get()来获取数组,而不是jQuery集合)

Or, avoid jQuery entirely if you want, no need to include a big library for something as simple as this: 或者,如果您愿意的话,完全避免使用jQuery,无需为此类简单的操作包含一个大型库:

const values = Array.prototype.map.call(
  document.querySelectorAll('.img-title'),
  element => element.value
);

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

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