簡體   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