Javascript 使用此函数在div内迭代输入的最佳方法是什么
我试图知道(但没有成功),在单击按钮后,用特定div中的特定类迭代所有输入元素的最佳方法是什么Javascript 使用此函数在div内迭代输入的最佳方法是什么,javascript,jquery,html,Javascript,Jquery,Html,我试图知道(但没有成功),在单击按钮后,用特定div中的特定类迭代所有输入元素的最佳方法是什么 <div> <input type="text" class="inputtext"> <input type="text" class="inputtext"> <input type="text" class="inputtext"> <input type="text" class="anotherclass"
<div>
<input type="text" class="inputtext">
<input type="text" class="inputtext">
<input type="text" class="inputtext">
<input type="text" class="anotherclass">
<input type="text" class="anotherclass">
<button class="full">click me</button>
</div>
谢谢你的关注 使用.map
var values = $(".inputtext").map(function() { return this.value }).get();
值
将是每个输入值的数组。使用JQuery方法:
$(".full").click(function() {
$(this).parent().children(".inputtext").each(function(){console.log($(this).val());});
});
工作小提琴:试试
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});
您可以使用each()
函数,有点像这样:
$(".full").click(function() {
$(this).parent().children(".inputtext").each(function(){
console.log($(this).val());
});
});
或者最好使用同级()
而不是像这样使用父级().children()
进行遍历
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});
完美!所以在我的例子中,根据这个事实,我只希望输入值靠近单击的按钮,我必须使用:$(this.parent().find(“.inputtext”).map(function(){return this.value}).get();不起作用,选择器已经正确,但是.val()只会给他第一个选定元素的值,他需要迭代它们。
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});