繁体   English   中英

替换HTML中的JS内容?

[英]Replacing JS content in HTML?

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

我正在尝试使用forEach函数显示newLinks页面的newLinks ,但它对我不起作用。 我不确定自己在做什么错,我想用newLinks替换.bio__content h4内容,所以我使用了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);
});

replace函数是一个字符串函数,它将字符串中的某个值替换为另一个值。 使用javascript将html添加到文档中时应使用的函数是$ .html() 另外,如果您使用join函数将所有链接加入到一个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> 


  
 
  
  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM