JavaScript / jQuery:选择更改事件未触发

时间:2013-11-14 03:50:12

标签: javascript jquery

我有一个问题,试图让一个单独的函数使用dropdown循环在for ... in列表的“更改”事件上附加多个单独的函数。 $('select')对象顶部没有方法'on'是Chrome调试器检测到的类型错误。

这是我的代码:(我没有太多的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 ","
    }
});

}

某些修复后的代码仍无效

这是我将它附加到popover 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();

    }

});

所以我的问题是如何纠正上面的代码以获得预期的输出(如代码中的注释)?

2 个答案:

答案 0 :(得分:0)

你宣布

var select = $('select'); // select object assigned to variable

但是然后覆盖for循环中的值

for (select in this) ...

也就是说,循环中的select与您在上面声明的不同。

答案 1 :(得分:0)

尝试这样的事情

            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
                });

            })