2015-12-11 41 views
2

我使用的是引導ComboBox pluginjQuery的上改變事件doen't工作

,我渲染mvc4 Razor視圖

@Html.DropDownListFor(model => model.CarFormatId, Model.CarFormats, "Select", new { @id = "SelectCarFormat", @class = "combobox form-control" }) 

內組合框和我使用jQuery獲取選擇改變試圖

$("#SelectCarFormat").on('change', function() { 
    alert('this is changed!');   
}); 

但我越來越沉默,用戶界面內沒有任何內容,沒有報告爲螢火蟲控制檯內的錯誤?

我在做什麼錯在這裏?

p.s.只是這裏要注意的是jQuery代碼被包裹在裏面on dom ready

編輯: 呈現的HTML代碼

<select id="SelectCarFormat" class="combobox form-control" 
     data-val-required="The SelectCarFormatId field is required." 
     data-val-number="The field SelectCarFormatId must be a number." data-val="true" display: none;> 
    <option value="">Select</option> 
    <option value="2">Format A</option> 
    <option value="3">Format B</option> 
</select> 

回答

5

然後,你必須使用事件委派:

$(document.body).on('change', '#SelectCarFormat', function() { 
    alert('this is changed!');   
}); 

似乎就已經隨着你使用的插件而改變,所以你正在查看的元素沒有任何註冊事件。


因爲這個插件的它被改成這樣:

<div class="combobox-container"> 
    <input type="hidden" name="normal" value=""> 
    <div class="input-group"> 
    <input type="text" autocomplete="off" placeholder="Select a State" class="combobox input-large form-control"> 
    <ul class="typeahead typeahead-long dropdown-menu" style="top: 34px; left: 0px; display: block;"> 
     <li data-value="Alabama" class=""><a href="#"><strong></strong>A<strong></strong>l<strong></strong>a<strong></strong>b<strong></strong>a<strong></strong>m<strong></strong>a<strong></strong></a> 
     </li> 
    </ul> <span class="input-group-addon dropdown-toggle" data-dropdown="dropdown"> <span class="caret"></span> <span class="glyphicon glyphicon-remove"></span> </span> 
    </div> 
</div> 
<select class="combobox input-large form-control" style="display: none;"> 
    <option value="" selected="selected">Select a State</option> 
    <!-- other options --> 
</select> 

The above one is taken from here.
正如你可以看到你的目標元素是不存在的,實際上它一直隱藏。所以你必須改變你的事件綁定到這個元素:

$(document.body).on('click', '.combobox-container li', function() { 
    alert('this is changed!');   
});