javascript - 如何使用 JavaScript 根据 Id 更新字符串中存在的 Html 内容?

标签 javascript jquery

我有 1. Html 字符串变量 2. 包含更改的对象

var htmlString = '\<body>\
                    <div class="shrek">\
                        <div class="trck">Object containing\
                            <div id ="head"> \
                                <strong>Object containing</strong>\
                            </div>\
                        </div>\
                    </div>\
                    <div id ="body"> String Variable String Variable String Variable</div>\
                    <div id ="foot">Similar Questions</div>\
                  </body>'

var obj = {
    'head': '<strong>I</strong> am new head'
}

我想用新内容更新 htmlString 并将此变量传递给服务。 最后 htmlstring 应该像

<body>
    <div class="shrek">
        <div class="trck">Object containing
            <div id="head"><strong>I</strong> am new head</div>
        </div>
    </div>
    <div id="body"> String Variable String Variable String Variable</div>
    <div id="foot">Similar Questions</div>
</body>

HtmlString 模式可以不同,如何根据 Id 更新字符串。

最佳答案

首先要小心你的报价,因为你有几个不匹配的实例。我建议使用 ' 来分隔字符串,以便您可以在其中使用 " 来分隔 HTML 中的属性值。

要解决您的实际问题,您可以使用 Object.keys() 从对象中获取键,其中包含要搜索的 id 属性,然后再循环它们检索元素并根据需要设置 html()。试试这个:

var htmlString = '<div class="shrek"><div class="trck">Object containing<div id="head"><strong>Object containing</strong></div></div></div><div id="body"> String Variable String Variable StringVariable</div><div id="foot">Similar Questions</div>';
var obj = {
  'head': '<strong>I</strong> am new head'
}

var $html = $(htmlString);
Object.keys(obj).forEach(function(k) {
  $html.find('#' + k).html(obj[k]);
});
$html.appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 如何使用 JavaScript 根据 Id 更新字符串中存在的 Html 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319465/

相关文章:

javascript - TypeError : $(. ..).daterangepicker 不是一个函数

javascript - PHP Echo SUM session 值和表单选择

javascript - 如何将价格包装在span正则表达式中?

javascript - 从上下文中删除时,jQuery 函数将不会运行

javascript - Highcharts 使用 TCPDF 将图表即时导出为 PDF

jquery - 为什么此代码在 IE8 和 IE7 中不起作用

javascript - 单击子 div 外部关闭灯箱

jquery - 将 jQuery 条件验证添加到动态生成的 HTML

javascript - focus() 方法仅在 Internet Explorer 中滚动到顶部

javascript - 使用jquery顺序调用多个函数