简体   繁体   English

替换HTML中的JS内容?

[英]Replacing JS content in HTML?

I'm trying to replace the .bio__content h4 text with the newLinks content I created in my JS file. 我正在尝试用我在JS文件中创建的newLinks内容替换.bio__content h4文本。

I'm trying to use the forEach function to display the newLinks to the page but it's not working for me. 我正在尝试使用forEach函数显示newLinks页面的newLinks ,但它对我不起作用。 I'm not sure what I'm doing wrong, I want to replace the the .bio__content h4 content with newLinks , so I used the replace() function. 我不确定自己在做什么错,我想用newLinks替换.bio__content h4内容,所以我使用了replace()函数。

Is this not right? 这样不好吗

HTML 的HTML

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

JS 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);
});

The replace function is a string function which replaces the a certain value within a string with another value. replace函数是一个字符串函数,它将字符串中的某个值替换为另一个值。 The function you should use to add html to a document using javascript is $.html() . 使用javascript将html添加到文档中时应使用的函数是$ .html() Also, it would be easier if you joined all links into one html string withe the join function and added it to the document. 另外,如果您使用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