[英]Unable to bind onChange event with select
I am trying to bind on-change event with my HTML select , but not successful in this, This is my HTML code 我试图用我的HTML select绑定on-change事件,但在此过程中不成功,这是我的HTML代码
<div class="size clearfix">
<form>
<label for="Size"><spring:theme code="product.variants.size"/></label>
<select id="Size">
<option>..</option>
<option>..</option>
<option>..</option>
</select>
</form>
</div>
And this is how, I am trying to bind onChange event 这就是我试图绑定onChange事件的方式
$(document).ready(function ()
$("#Size").change(function () {
var url = "";
var selectedIndex = 0;
$("#Size option:selected").each(function () {
url = $(this).attr('value');
selectedIndex = $(this).attr("index");
});
if (selectedIndex != 0) {
window.location.href=url;
}
});
});
But somehow this is not working, not sure what I am doing wrong.Just to add all this code is in $(document).ready(function ()
By not working means, event is not getting fired at all 但是以某种方式这是行不通的,不确定我在做什么错。只需将所有这些代码添加到
$(document).ready(function ()
通过不起作用的方式,事件就不会被触发
There is no index
attribute, you should read the selectedIndex
property of the select element. 没有
index
属性,您应该阅读select元素的selectedIndex
属性。
var selectedIndex = this.selectedIndex;
Also since you don't have a multiple select element, the each
call here is redundant. 另外,由于您没有多个选择元素,因此此处的
each
调用都是多余的。 this.value
gives you the current select's value. this.value
为您提供当前选择的值。
$("#Size").change(function () {
if (this.selectedIndex > 0) {
// Assuming your options have `value` attribute
window.location.href= this.value;
}
});
For the sake of completeness for getting the index
of the selected option in the each
callback you could use the index
method: 为了完整获取
each
回调中所选选项的index
,可以使用index
方法:
$(this).index();
Since attr('index')
returns an undefined
value your condition is always falsy. 由于
attr('index')
返回一个undefined
值,因此您的情况总是虚假的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.