jQuery 加载动态“选择”选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8349888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:24:16  来源:igfitidea点击:

Loading dynamic "chosen" select elements

ajaxjquery-pluginsjquery

提问by Brian Anderson

I am using the jQuery plugin chosen (by Harvest). It is working fine on (document).ready, but I have a button that, when clicked, uses ajax to dynamically create more select objects that I want to use the "chosen" feature. However, only the original select elements have the "chosen" features, and the new (dynamically created) do not work. I am using jQuery.get to append the new elements. Here is a sample of the code:

我正在使用选择的 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 :-(
    });
});

I was thinking that I need a .live() function somewhere, but I haven't been able to figure that out yet. Any help is much appreciated!

我在想我在某处需要一个 .live() 函数,但我还没有弄清楚。任何帮助深表感谢!

Note - I am not trying to dynamically load new options, as specified in the documentation usingtrigger("liszt:updated");

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

采纳答案by RightSaidFred

Ensure that the responseelements have the selectclass.

确保response元素具有select类。

console.log( response );  // to verify

May also be a good idea to only apply the plugin to the new element(s).

将插件仅应用于新元素也可能是一个好主意。

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

Also, if /myurlis returning an entire HTML document, you may get unpredictable results.

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

回答by Rober Dote

after you code (fill the select) .write this

编码后(填写选择)。写这个

$(".select").trigger("chosen:updated");

回答by Judson

I had a similar problem with Chosen. I was trying to dynamically add a new select after the user clicks on a link. I cloned the previous select and then added the clone, but Chosen options would not work. The solution was to strip the Chosen class and added elements, put the clone in the DOM and then run chosen again:

我对 Chosen 也有类似的问题。我试图在用户点击链接后动态添加一个新的选择。我克隆了之前的选择,然后添加了克隆,但选择的选项不起作用。解决方案是剥离 Chosen 类并添加元素,将克隆放入 DOM 中,然后再次运行 selected :

clonedSelect.find('select').removeClass('chzndone').css({'display':'block'}).removeAttr('id').next('div').remove();
mySelect.after(clonedSelect);
clonedSelect.find('select').chosen();

回答by TomTom

one way you can use chosen with ajax:

您可以使用 ajax 选择的一种方式:

$.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: search
}).done(function(data){
    $.each(data, function(){
    $('<option />', {value: this.value, text: this.text}).appendTo(selectObj);
    });
    chosenObj.trigger('liszt:updated');
});

where selectObj is particular select object

其中 selectObj 是特定的选择对象

But ...

但 ...

Chosen is implemented very bad. It has several visual bugs, like: select some option, then start searching new one, then remove selected and the keep typing - you will get 'Select some options' extended like 'Select some options search value'. It doesn't support JQuery chaining. If you will try to implement AJAX you will notice, that when you loose focus of chosen, entered text disappears, now when you will click again it will show some values. You could try to remove those values, but it will be a hard time, because you cannot use 'blur' event, because it fires as well when selecting some values. I suggest not using chosen at all, especially with AJAX.

选择的实施非常糟糕。它有几个视觉错误,例如:选择某个选项,然后开始搜索新选项,然后删除选定的选项并继续输入 - 您将获得“选择一些选项”扩展,例如“选择一些选项搜索值”。它不支持 JQuery 链接。如果您尝试实现 AJAX,您会注意到,当您松开所选的焦点时,输入的文本会消失,现在当您再次单击时,它将显示一些值。您可以尝试删除这些值,但这会很困难,因为您不能使用 'blur' 事件,因为它在选择某些值时也会触发。我建议根本不要使用 selected,尤其是 AJAX。

回答by Dario Ferrer

1.- Download Livequery pluginand call it from your page.

1.- 下载Livequery 插件并从您的页面调用它。

2.- Release the Kraken: $(".select").livequery(function() { $(this).chosen({}); });

2.- 释放海妖: $(".select").livequery(function() { $(this).chosen({}); });

回答by Fawad

This is an example of Chosen dynamically loading new options form database using ajax every time Chosen is clicked.

这是Chosen 每次单击Chosen 时使用ajax 动态加载新选项表单数据库的示例。

$('.my_chonsen_active').chosen({
    search_contains:true
});
$('.my_chonsen_active').on('chosen:showing_dropdown', function(evt, params){
     id_tosend=$(this).attr("id").toString();
     $.get("ajax/correspondance/file.php",function(data){ 
     $('#'+id_tosend).empty();
     $('#'+id_tosend).append(data);
     $('#'+id_tosend).trigger("chosen:updated");
   });
});