简体   繁体   English

js-使用replace方法替换html元素

[英]js - using replace method to replace html element

I have a question. 我有个问题。 I have a work this morning but i don't know how to do it. 我今天早上有工作,但我不知道该怎么做。 My work here (html): 我在这里的工作(html):

<div class="demo">
    <p>this is demo text</p>
</div>

Here is my JS: 这是我的JS:

var tempdata = $(".demo").text();
var replacedata = tempdata.replace("text","<span>1234</span>");

Look everything ok. 看起来一切正常。 But result is: this is demo <span>1234</span> . 但是结果是: this is demo <span>1234</span> This isn't my result I want. 这不是我想要的结果。 How to make in this string become a HTMLelement by using replace method? 如何通过使用replace方法使此字符串成为HTMLelement?

document.getElementById('demo').firstElementChild.innerHTML =
  document.getElementById('demo').firstElementChild.innerHTML.replace(/text/, "<span>1234</span>");

When assigning the value back, use .html() instead of .text() so it won't encode it, like this: 将值.html()回时,请使用.html()而不是.text()这样它就不会对其进行编码,如下所示:

var tempdata = $(".demo").text();
var replacedata = tempdata.replace("text","<span>1234</span>");
$(".demo").html(replacedata);​​​​​​

You can see a demo here 你可以在这里看到一个演示

Also, you can pass a method to .html() if you're doing this to many elements, like this: 另外,如果您要对许多元素执行以下操作,则可以将方法传递给.html()

$(".demo").html(function(i, h) {
    return h.replace("text","<span>1234</span>");
});​

Note this uses .html() as the source as well, but makes no difference for the example code. 请注意,这也使用.html()作为源,但对示例代码没有影响。

You can see a demo of that here 你可以在这里看到一个演示

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

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