2012-03-19 28 views
2

這裏火災是我的代碼:jQuery的.change()僅在第一變化

$.each (t.config.industry, function (i, v) { 
    $(v).change(function() { 
     console.log("Industry change!"); 
    }); 
}); 

t.config.industry<select> ID的數組。 t.config.industry: ["#W2549_Sl", "#W2601_Sl", "#W2654_Sl"]我在頁面上有幾個<select>框,我正在跟蹤它們。任何時候他們中的任何一個都會改變我想開火。

很明顯,我試圖做的不僅僅是console.log,但爲了這篇文章的緣故,我將其限制爲這個。在我的網站上,console.log只在第一次更改時打印一次。在後續更改<select>下拉菜單時,它不會觸發。

以前有人看過這個嗎?

注:我根本無法更改HTML標記。

+0

這是一個有點硬,沒有看到一些標記破譯,但你含在每個功能的變化。每個應用程序通常會爲批處理中的每個元素應用一次函數,我從來沒有在每個元素中嵌套一個更改函數。 – 2012-03-19 15:32:32

+0

標記只是一堆選擇框。但我無法改變加價。這很難解釋,但我堅持了加價。 – 2012-03-19 15:46:33

回答

-2

您正在爲每個選項設置聽衆。只把它放在你的選擇上!

0

您需要v(您id)之前加入#,這個選擇工作

$.each(t.config.industry, function (i, v) { 
    $("#" + v).change(function() { 
     console.log("Industry change!"); 
    }); 
}); 
+0

t.config.industry是我所有選擇框ID的數組。 – 2012-03-19 15:38:59

+0

@JesseAtkinson更新,試試:-)如果這不起作用,那麼請在你的問題中發佈你的數組的實際內容 – ManseUK 2012-03-19 15:41:21

0

嘗試重寫它在一個這樣的方式HTML

 <select id="main_industry"> 
      <?foreach ($industry as $item){?> 
      <option value="<?=$item['id']?>"><?=$item['title']?></option> 
      <?}?> 
     </select> 

JAVASCRIPT

$('#main_industry').change(function() { 
     // your stuff here 
     console.log ($(this).val()); 
    } 
1

如果你可以添加一個公共類到每個e選擇要監視的元素,這將極大地簡化您的代碼。試試這個(爲on方法所需的jQuery 1.7):

$(document).on('change','select.monitorme', function() { 
    console.log($(this).attr('id')+' changed!'); 
}); 

$.each (t.config.industry, function (i, v) { 
    $(v).change(function() { 
     $(this).addClass('monitorme'); // or just add the class to your markup 
    }); 
}); 
4

我目睹了此行爲時多選擇元素的ID是不是唯一的。爲了解決這個問題,我簡單地刪除了id,定義了一個類,並修改了jQuery選擇器以使用指定的類。例如:

<select class="some_value" some_id="<%= some[:id] %>"> 

    $(".some_value").change(function() { 
     var some_id = $(this).attr("some_id"); 
     alert('some_id: ' + some_id); 
    }); 

坦率地說,我認爲這是jQuery中的一個bug。爲什麼它應該成功一次,然後再失敗?

0

對於asp.net正確地在我的項目中工作。請勾選如果對你的工作

<asp:DropDownList ID="txtvisitname" AutoPostBack="true" class="txtno" AppendDataBoundItems="true" 
       runat="server" onchange="return selectChange()"> 
       <asp:ListItem Text="--SELECT--" Value="0" /> 
       <asp:ListItem Text="VISIT1" Value="VISIT1" /> 
       <asp:ListItem Text="VISIT2" Value="VISIT2" /> 
       <asp:ListItem Text="VISIT3" Value="VISIT3" /> 
       <asp:ListItem Text="VISIT4" Value="VISIT4" /> 
       <asp:ListItem Text="VISIT5" Value="VISIT5" /> 
       <asp:ListItem Text="Unscheduled VISIT" Value="Unscheduled VISIT" /> 
      </asp:DropDownList> 

功能

selectChange() { 

      if ($("[id*=txtvisitname]").val() == "Unscheduled VISIT") { 
       $(".other").show(); 
      } else { 
       $(".other").hide(); 
      } 
    }