我将包含 html 的字符串附加到主 div 中。该字符串包含由某些我无法修改的函数生成的下拉列表。现在,对于包含带有下拉列表的 html 的字符串,我想设置下拉列表的选项,然后附加 div
var stringHtml = "<div> <select>"+ someFunction() + "</select></div>";
jQuery('#mainDiv').append(stringHtml);
所以上面的 someFunction() 有助于获取选择的选项,然后附加选项
我想做这样的事情
jQuery(stringHtml).find("select option[value=\"" + sumeValue + "\"]").attr('selected', 'selected');
然后附加 html,以便我选择所需的值
谢谢
最佳答案
这里的问题是您仍在将字符串本身插入到页面中。然而,您应该插入的是调用 jQuery(stringHtml)
时创建的 jQuery 对象,因为这是受您的代码影响的对象。结果应如下所示:
var stringHtml = "<div> <select>"+ someFunction() + "</select></div>";
var html = jQuery(stringHtml); //save the whole string as an object
html.find("select").val(sumeValue); // alter the object
jQuery('#mainDiv').append(html); // insert the whole object to the page
这是fiddle 。请注意轻微的优化 - 无需创建这个复杂的选项选择器,您只需设置选择器本身的值即可。
关于javascript - jQuery:将选定的下拉选项设置为 html 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606908/