加载动态"选择"选择元素

Bri*_*son 8 ajax jquery jquery-plugins

我正在使用所选的jQuery插件(由Harvest).它在(document).ready上运行正常,但我有一个按钮,当单击它时,使用ajax动态创建更多选择对象,我想使用"选择"功能.但是,只有原始选择元素具有"选定"功能,而新(动态创建)功能不起作用.我正在使用jQuery.get来追加新元素.以下是代码示例:

jQuery(".select").chosen();//this one loads correctly
jQuery("#add-stage").click(function() {
    jQuery.get('/myurl',{},function(response) {
            //response contains html with 2 more select elements with 'select' class
            jQuery('#stages').append(response);
        jQuery(".select").chosen();//this one doesn't seem to do anything :-(
    });
});
Run Code Online (Sandbox Code Playgroud)

我在想某个地方需要一个.live()函数,但我还没有想到它.任何帮助深表感谢!

注意 - 我没有尝试动态加载新选项,如使用文档中所指定的那样 trigger("liszt:updated");

Rig*_*red 6

确保response元素具有select类.

console.log( response );  // to verify
Run Code Online (Sandbox Code Playgroud)

将插件应用于新元素也是一个好主意.

jQuery(".select").chosen();

jQuery("#add-stage").click(function() {
    jQuery.get('/myurl',{},function(response) {
        console.log( response ); // verify the response

        var $response = $(response);  // create the elements

        $response.filter('.select').chosen(); // apply to top level elems
        $response.find('.select').chosen();   // apply to nested elems
        $response.appendTo('#stages');
    });
});
Run Code Online (Sandbox Code Playgroud)

此外,如果/myurl返回整个HTML文档,您可能会得到不可预测的结果.


小智 5

在编写代码(填写选择内容)后,编写此代码

$(".select").trigger("chosen:updated");
Run Code Online (Sandbox Code Playgroud)