如何从javascript(事件)对象获取选定值
我正在尝试从事件中获取所选值 我不知道用哪种方法得到这个值。有什么建议吗如何从javascript(事件)对象获取选定值,javascript,jquery,html-select,jquery-events,Javascript,Jquery,Html Select,Jquery Events,我正在尝试从事件中获取所选值 我不知道用哪种方法得到这个值。有什么建议吗 //update item quantity cartList.on('change', 'select', function (event) { var row = $(event.target).parents('.product'); updateItemQuantity(row.data('row_id'), QUANTITY_IS_SELECTED_VALUE); quickUpdateCart
//update item quantity
cartList.on('change', 'select', function (event) {
var row = $(event.target).parents('.product');
updateItemQuantity(row.data('row_id'), QUANTITY_IS_SELECTED_VALUE);
quickUpdateCart();
});
事件。目标是触发事件的元素。您可以使用jQuery通过执行$(event.target).val()
读取其值。您还可以使用this
关键字,该关键字包含相同的元素($(this).val()
)
除了使用jQuery,您还可以通过this.options[this.selectedIndex].text的普通DOM方法检索值。target
是触发事件的元素。您可以使用jQuery通过执行$(event.target).val()
读取其值。您还可以使用this
关键字,该关键字包含相同的元素($(this).val()
)
除了使用jQuery,您还可以通过this.options[this.selectedIndex].text的普通DOM方法检索值。jQuery中的.val()
方法返回或设置所选元素的value属性。此方法返回第一个匹配元素的value属性的值
$(selector).off('change').on('change', function () {
var selectedValue = $(this).val();
alert(selectedValue);
//Your other logic here
});
jQuery中的.val()
方法返回或设置所选元素的value属性。此方法返回第一个匹配元素的value属性的值
$(selector).off('change').on('change', function () {
var selectedValue = $(this).val();
alert(selectedValue);
//Your other logic here
});
使用纯javascript
可以找到所选选项和所有相关信息:
console.log(event.target.selectedOptions[0].value);
console.log(event.target.selectedOptions[0].label);
使用纯javascript
可以找到所选选项和所有相关信息:
console.log(event.target.selectedOptions[0].value);
console.log(event.target.selectedOptions[0].label);
试试这个
event.target.options[event.target.options.selectedIndex].text
试试这个
event.target.options[event.target.options.selectedIndex].text
您可以将selectby类作为目标,然后添加onChange处理程序,并获取值
var selectItem = document.querySelector("select.cartList");
selectItem.addEventListener("change", function(event) {
var newChangedValue = event.target.value;
console.log(newChangedValue);
});
您可以将selectby类作为目标,然后添加onChange处理程序,并获取值
var selectItem = document.querySelector("select.cartList");
selectItem.addEventListener("change", function(event) {
var newChangedValue = event.target.value;
console.log(newChangedValue);
});
event.target.value
可能重复的是,我刚刚实现(event.target是触发事件的元素)event.target.value
可能重复的是,我刚刚实现(event.target是触发事件的元素)event.target.value
和this.value
避免了jQuery实例化和val()
方法调用。如果您已经有了变量,直接属性访问会更有效。@Taplar True,我通常会使用vanilla.value
来代替,但它并不适用于selects,在旧浏览器中,您必须使用selectedIndex解决方法。不过,我会更新我的答案以提及它。event.target.value
和this.value
避免了jQuery实例化和val()
方法调用。如果您已经有了变量,直接属性访问会更有效。@Taplar True,我通常会使用vanilla.value
来代替,但它并不适用于selects,在旧浏览器中,您必须使用selectedIndex解决方法。不过,我会更新我的答案以提及它。这并不能提供问题的答案。若要评论或要求作者澄清,请在其帖子下方留下评论。-我也在寻找同样的解决方案,但在这里没有找到没有jquery的解决方案。所以我想分享一下我是如何在没有jquery的情况下获得它的。这并不能回答这个问题。若要评论或要求作者澄清,请在其帖子下方留下评论。-我也在寻找同样的解决方案,但在这里没有找到没有jquery的解决方案。所以我想分享一下我是如何在没有jquery的情况下获得它的。