如何在 DOM 中循环浏览输入范围滑块列表并使用每个循环捕获值

How to loop through a list of input range sliders in the DOM and capture values with an each loop

本文关键字:循环 列表 DOM 浏览 范围 输入      更新时间:2023-09-26

下面是一个函数,旨在循环浏览一系列具有特定 id 属性的输入滑块并捕获它们的值。它不起作用。为什么哦为什么?谢谢。

JS小提琴示例

http://jsfiddle.net/V93D4/1/

.HTML

<button id='button'>save</button>
<input id="pitchInput_1" type='range'></input>
<input id="pitchInput_2" type='range'></input>

JAVASCRIPT

 $('#button').click(function(){
     $('input[id^="pitchInput_"]').each(function(){
           alert(this.id);
           alert($('input[id^="pitchInput_"]').val()); // Doesn't capture correct val of BOTH sliders. 
        });

    });

是的,val()只得到第一个。

var values = $('input[id^="pitchInput_"]').map(function() {
    return $(this).val();
});
alert(values.join(''n'));

在这里,values是滑块值的数组。

对代码进行一些修改就可以了。

<input id="pitchInput_1" type='range'></input>
<input id="pitchInput_2" type='range'></input>

现在,每个循环都会计算滑块的正确值。

$('#button').click(function(){
 $('input[type="range"]').each(function(){
     alert(this.id);
     alert($(this).val()); 
  });
});

在此处查看演示

除此之外,您只需修改此行即可获得适当的值。

alert($('input[id^="pitchInput_"]').val());

有了这个。

alert($(this).val());

希望对您有所帮助。