【问题标题】:jQuery: set dropdown options selected to the html stringjQuery:将选择的下拉选项设置为 html 字符串
【发布时间】:2014-05-01 15:53:59
【问题描述】:

我将包含 html 的字符串附加到主 div。此字符串包含由我无法修改的某些函数生成的下拉列表。现在到这个包含带有下拉列表的 html 的字符串我想设置下拉列表的选项,然后附加 div

var stringHtml = "<div> <select>"+ someFunction() + "</select></div>";
jQuery('#mainDiv').append(stringHtml);

所以上面的 someFunction() 有助于获取 select 的选项,然后附加选项

我想做这样的事情

jQuery(stringHtml).find("select option[value=\"" + sumeValue + "\"]").attr('selected', 'selected');

然后附加 html 以便我选择所需的值

谢谢

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    这里的问题是您仍在将字符串本身插入到页面中。但是,您应该插入的是调用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。注意轻微的优化 - 不需要创建这个复杂的选项选择器,您可以简单地设置选择本身的值。

    【讨论】:

    • 感谢您的回答,但有一个问题,var html 仅返回选项,这就是小提琴工作的原因,但如果您将 html 添加到未显示的 stringHtml
    • jsfiddle.net/6bLdM/1 我已插入 Hello 是未显示的 html
    • @user3273621,抱歉,没抓住重点。很容易治愈,请看答案更新。小提琴更新:jsfiddle.net/6bLdM/2
    • @user3273621,只是为了让您知道 - 接受答案可以帮助其他有类似问题的用户,以防他们用谷歌搜索您的问题。这样你就可以为 SO 社区做出贡献。这不仅适用于本帖,也适用于您的其他帖子。
    【解决方案2】:

    试试这个:

    jQuery(stringHtml).find("select option[value='" + sumeValue + "']").attr('selected', 'selected');
    

    【讨论】:

    • 不,我试过了,但没用。仅设置默认值。我需要通过应用选定的下拉值生成 stringHtml 的解决方案
    • 你能创作小提琴吗??
    猜你喜欢
    • 2014-06-28
    • 2011-02-10
    • 2010-12-14
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2013-01-28
    • 2012-09-08
    • 2017-01-26
    相关资源
    最近更新 更多