[英]JavaScript/jQuery: Select on change event not firing
我遇到這個問題,試圖讓一個單獨的函數在for ... in
循環中在dropdown
列表的“更改”事件上附加多個單獨的函數。 $('select')
對象頂部沒有方法'on'
是Chrome調試器檢測到的Type錯誤。
這是我的代碼:(我對JavaScript / jQuery的了解不多,所以請耐心等待我的編碼)
function AKaizerDropdown(HiddenFeild) { //#id of hidden field passed as parameter
var select = $('select'); // select object assigned to variable
var selectcount = 0;
var Selecthold=new Array();
for (select in this) {
select.on('change', function() {
var SelectedIndex = this.attr('selectedIndex');
selecthold[selectcount] = [select.attr('id'), selectedindex];
//Select ID and Selected index assigned as an array into Selecthold Array element
});
selectcount +=1;
}
var item= new array();
//Elements in selecthold array printed onto hidden field
for (item in selecthold) {
$(HiddenFeild).val += item[0] + item[1]; //Assigns values to element Hiddenfield in DOM
}
}
編輯代碼:
$.fn.AKaizerDropdown = function (HiddenFeild) {
var select_ = $(this).find('select');
var selectcount = 0;
var Selecthold=new Array();
select_.each(function () {
$(this).on('change', function () { //everything runs fine except dropdownlist doesn't enter into this event when an item is chosen
var SelectedIndex = this.selectedIndex;
Selecthold[selectcount] = [this.id, Selectedindex];
});
});
var button_ = $(this).find('input')
button_.on('click', function () {
for (item in Selecthold) {
$(HiddenFeild).val += item[0] + item[1]+','; //Assigns values to element Hiddenfeild in DOM seperated by ","
}
});
}
某些固定代碼仍然無法正常工作
這是我將其連接到彈出式Bootstrap(twitter 2.3.2)的部分。
//think the problem lies here where the pop up seems to re-render the same same html found in ($#KaizerDragon") where all JavaScript is probably discarded?
$("#ContentPlaceHolder1_ADragonTreeviewt41").popover({
html: true, container: 'body',
trigger: 'click',
content: function () {
$(function () {
$("#KaizerDragon").AKaizerDropdown();
});
return $("#KaizerDragon").html();
}
});
所以我的問題是如何糾正上述代碼以獲得預期的輸出(如代碼中的注釋所示)?
你是在宣告
var select = $('select'); // select object assigned to variable
但是然后覆蓋您的for循環中的值
for (select in this) ...
也就是說,循環內部的select
與您上面聲明的不同。
嘗試這樣的事情
select.each(function(){
$(this).on('change', function() {
var SelectedIndex = this.selectedIndex;
Selecthold[selectcount] = [this.id, SelectedIndex];
//Select ID and Selected index assigned as an array into Selecthold Array element
});
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.