问题描述
我正在使用选择的 jQuery 插件(由 Harvest 提供).它在 (document).ready 上运行良好,但我有一个按钮,单击该按钮时,它使用 ajax 动态创建更多我想使用选择"功能的选择对象.但是,只有原始的选择元素具有选择"功能,而新的(动态创建的)不起作用.我正在使用 jQuery.get 附加新元素.以下是代码示例:
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(".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 :-(
});
});
我在想我在某个地方需要一个 .live() 函数,但我还没有弄清楚.非常感谢任何帮助!
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!
注意 - 我没有尝试动态加载新选项,如使用文档中指定的那样 trigger("liszt:updated");
推荐答案
确保 response
元素具有 select
类.
Ensure that the response
elements have the select
class.
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');
});
});
另外,如果 /myurl
返回整个 HTML 文档,您可能会得到不可预知的结果.
Also, if /myurl
is returning an entire HTML document, you may get unpredictable results.
这篇关于加载动态“选择"选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!