用HTML替换JS内容?

时间:2016-07-11 03:15:14

标签: javascript jquery html

我尝试将.bio__content h4文本替换为我在JS文件中创建的newLinks内容。

我尝试使用forEach功能向页面显示newLinks,但它对我不起作用。我不确定自己做错了什么,我想将.bio__content h4内容替换为newLinks,因此我使用了replace()功能。

这不对吗?

HTML

 <div class="bio__content">
     <h1 itemprop="name">Name</h1>
        <div>
           <h4><%- profile.designations %></h4>
         </div>
  <div>

JS

var designation = JSContext.profile.designations.split(", ");
// designation = ['CAP', 'AEA', 'AAA']

var newLinks = designation.map(function(x) {
return "<a class='modal'>" + x + "</a>" });
// newLinks = ["<a class='hey'>CAP</a>", "<a class='hey'>AEA</a>", "<a class='hey'>AAA</a>"]

newLinks.forEach(function (e) {
  $(".bio__content").text().replace(".bio__content h4", e);
});

1 个答案:

答案 0 :(得分:1)

replace函数是一个字符串函数,它将字符串中的某个值替换为另一个值。您应该使用javascript将html添加到文档的函数是$.html()。此外,如果您将所有链接加入到join function的一个html字符串中并将其添加到文档中会更容易。

var designation = //JSContext.profile.designations.split(", ");
            designation = ['CAP', 'AEA', 'AAA']
            
            var newLinks = designation.map(function(x) {
            return "<a class='modal'>" + x + "</a>" });
            // newLinks = ["<a class='hey'>CAP</a>", "<a class='hey'>AEA</a>", "<a class='hey'>AAA</a>"]
            
             var linksString = newLinks.join("\n");
            $(".bio__content h4").html(linksString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bio__content">
             <h1 itemprop="name">Name</h1>
                <div>
                   <h4><%- profile.designations %></h4>
                 </div>
          <div>

相关问题