假设我有这些HTML对象:
<button id="addMore" class="button">+</button>
<div id="fieldList">
<input type="text" name="gsm[]" placeholder="GSM" required>
<input type="text" name="gsm[]" placeholder="GSM" required>
<input type="text" name="gsm[]" placeholder="GSM" required>
</div>
现在,我想用JavaScript循环浏览它们中的每一个。每个输入文本都有不同的值。这是我尝试过的(当前代码是一个较大代码的小片段(:
$('input[name^="gsm"]').each(function(i,obj) {
var eachGsm = $(this).val();
"This line has " + eachGsm[i] + ", as the value." + "%0D%0A" +
});
当运行这个时,脚本会给我:[object Object]
。正确的方法是什么?
您已经在元素列表上进行迭代,因此this
已经是您想要的值。
<button id="addMore" class="button">+</button>
<div id="fieldList">
<input type="text" name="gsm[]" placeholder="GSM" value='1' required>
<input type="text" name="gsm[]" placeholder="GSM" value='2' required>
<input type="text" name="gsm[]" placeholder="GSM" value='3' required>
</div>
$('document').ready(()=>{
$('input[name^="gsm"]').each(function(i,obj) {
var eachGsm = $(this).val();
console.log("each: " + eachGsm);
});
})
在这种情况下,您可以简单地执行
$('input[name^="gsm"]').each(function(i) {
console.log("This line has " + this.value + ", as the value." + "%0D%0A")
});
在该函数的上下文中,this
是引用HTMLinput
元素的对象,this.value
是用户输入的文本内容。
一个可运行的示例:https://jsfiddle.net/23ao7mup/1/