簡體   English   中英

jQuery - 用於檢測是否已選擇HTML select選項的事件處理程序

[英]jQuery - event handler to detect if HTML select option has been selected

當select選項中的任何選項被更改時,如何在jQuery中檢測到?

例如[偽代碼]:

event handler function -> option changed(){      
  //do some stuff
}

編輯:

我有以下選擇:

<select id = "selectattribute">
  <OPTION VALUE="0">Choose Attribute</OPTION>
  <?php echo($options);?>
</select>

我在jQuery中嘗試這個:

$(document).ready(function() {
  $("#selectattribute").change(function() {
     alert('Handler for .change() called.');
  });
});

什么都沒發生......功能不是觸發。

編輯:當我使用$("#select")而不是$("#selectattribute")...can you not apply it to particular select tags?

關於更改處理程序的jQuery文檔

<form>
  <input class="target" type="text" value="Field 1" />
  <select class="target">
    <option value="option1" selected="selected">Option 1</option>
    <option value="option2">Option 2</option>
  </select>
</form>
<div id="other">
  Trigger the handler
</div>

事件處理程序可以綁定到文本輸入和選擇框:

$('.target').change(function() {
  alert('Handler for .change() called.');
});

你的代碼使用鼠標在Firefox中工作,請看這個小提琴

但是,根據此錯誤報告,使用鍵盤是另一回事

為了解決這個問題,我添加了一個按鍵處理程序來從元素中移除焦點然后重新聚焦,就像這個小提琴一樣

如果在使用鼠標時未觸發更改事件,請檢查php代碼呈現的選項。 尋找可能“打破”select標簽的結構。

$("select").change(function() {})

看起來你的JQuery沒有加載,首先檢查它是否已加載

    //case if mini jQueryis not used replace with window.jQuery
    if (window.$) {
    console.debug('jQuery is loaded ');
    } else {
    console.debug('jQuery is not loaded ');
    }

試試綁定:

  $("#selectattribute").bind('change', function() {
     alert('Handler for .change() called.');
  });

或更改jQUery中的函數:

  $("#selectattribute").change(
     function() {
        alert('Handler for .change() called.');
     }
  ); 

也許還有另一個標簽,其id被命名為“selectattribute”。標簽id應該是唯一的。如果有多個id,jQuery將使用第一個id。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM