我需要帮助循环遍历 html 页面中的所有选择标签并在每次更改时运行一些函数
<div id="product_options">
<label>Color</label>
<select name="productOptions" id="colorOpt" style="margin-bottom:10px;">
<option value="1">White</option>
<option value="3">Blue</option>
</select>
<label>Size</label>
<select name="productOptions" id="sizeOpt" style="margin-bottom:10px;">
<option value="2">9oz</option>
<option value="4">10oz</option>**strong text**
</select>
</div>
主 div 内的所有内容都是变量,包括标签、名称和 id
我想要做的就是有人更新我需要弄清楚他们选择的选择元素之一并获取值的选定选项之一。因此,例如,如果他们将颜色选项更新为蓝色,我需要触发 jquery 中的调用以显示 id colorOpt 的选择元素已更新为值 3
我完全不知道如何做到这一点。以此开始,但不确定它是否正确
$('#product_options').select("select").each(function(selected, index) {
});
最佳答案
看起来您开始认为需要循环遍历每个选择...但是既然您说您需要“弄清楚他们选择了哪个选择元素”,您可以依赖 this
change
内的关键字回调。
fiddle :http://jsfiddle.net/vpqh3kjz/
代码:
// Every time someone updates either selected option fire a callback
$('#product_options select').change(function () {
// `this` represents the element that changed
var id = this.id;
var value = this.value;
// Do something with your data here
console.log('select element id ' + id + ' was updated with ' + value);
});
关于javascript - jquery 在选项更改时循环选择标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27051484/