繁体   English   中英

无法将select绑定onChange事件

[英]Unable to bind onChange event with select

我试图用我的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>

这就是我试图绑定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;
      }
    });
});

但是以某种方式这是行不通的,不确定我在做什么错。只需将所有这些代码添加到$(document).ready(function ()通过不起作用的方式,事件就不会被触发

没有index属性,您应该阅读select元素的selectedIndex属性。

var selectedIndex = this.selectedIndex;

另外,由于您没有多个选择元素,因此此处的each调用都是多余的。 this.value为您提供当前选择的值。

$("#Size").change(function () {
   if (this.selectedIndex > 0) {
      // Assuming your options have `value` attribute 
      window.location.href= this.value; 
   }
});

为了完整获取each回调中所选选项的index ,可以使用index方法:

$(this).index();

由于attr('index')返回一个undefined值,因此您的情况总是虚假的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM