如何使用存储在数组中的select2对象事件?

时间:2017-01-19 12:03:48

标签: javascript jquery events select2 opentext

我试图破解一些Opentext表单并且我已创建并在下面包含我的select2对象的数组。如何使用触发事件的对象的数组索引?或者有更好的方法吗?

joblink变量是一个隐藏元素,用于存储由opentext

编写和读取的值
for(var b = 0; b <= 15; b++){

            JobSelect[b] = $('#Job' + (b + 1) + 'Trans').select2({ width: '100%', Height: '100%' }).on('change', function(e){

                $(joblink[b]).val(this.value);

            });

            if ($(joblink[b]).val() != '')
            {
                $(JobSelect[b]).val($(joblink[b]).val()).trigger("change");
            }   
        }

1 个答案:

答案 0 :(得分:0)

这是我建议的解决方案的jsFiddle链接: https://jsfiddle.net/bindrid/ujna54an/3/

评论是内联的:

    for (var b = 0; b <= 15; b++) {

        // in your event handler, add a second parameter
        JobSelect[b] = $('#Job' + (b + 1) + 'Trans').select2({ width: '100%', Height: '100%' }).on('change', function (e, eData) {
            // puts the selected value in the job link

            // and put the variable here
            $(joblink[eData]).val(this.value);

        });

        //If not blank,  makes what ever in job link the selected value so it will put the value back in the job link
        // seems circular.
        if ($(joblink[b]).val() != '') {

            // add b as second parameter 
            $(JobSelect[b]).val($(joblink[b]).val()).trigger("change", b);
        }
    }

但是,如果您的唯一目的是将select同步到链接,只需将上述代码替换为此

即可
    // set up all selects 
    $('select').select2({ width: '100%', Height: '100%' });

    $.each(joblink, function (idx, item) {
        var link = $(item).val();

        if (link.length > 0) {
            $('#Job' + (idx + 1) + 'Trans').val(link).trigger('change');

        }
    })