我有多个文本节点,我想用 html 替换其中的一些文本:
<pre>{
"data": [
{
"source": "<a href=www.e.com>e.com</a>",
"created_time": "2015-11-13T06:16:09+0000",
"id": "913680432051814"
},
{
"source": "<a href=www.e.com>e.com</a>",
"created_time": "2015-11-13T06:16:02+0000",
"id": "913680355385155"
},
{
"source": "<a href=www.e.com>e.com</a>",
"created_time": "2015-11-13T06:16:00+0000",
"id": "913680332051824"
}
</pre>
我要添加<a>
标记到 ID 号。
我正在尝试:
x=$("pre")
.contents()
.filter(function() {
return this.nodeType === 3
});
尝试替换任何元素。我正在尝试 x[0]
rep = x[0].data.replace(//\"id\": \"(.*)\",/, "/\"id\": \"<a href=\"https:example.com/\$1\">$1</a>\"")
然后尝试
x[0].replaceWith(rep)
它说:x[0].replaceWith not a function
那么如何用html元素替换文本呢?
最佳答案
我尝试了下面的方法,它有效。使用 $(this) 有效。
x=$("pre")
.contents()
.filter(function() {
return this.nodeType === 3
})
.each(function(){
rep = this.data.replace(//\"id\": \"(.*)\",/, "/\"id\": \"<a href=\"https:example.com/\$1\">$1</a>\"")
$(this).replaceWith(rep); //when i used $(this) it worked.
})
关于javascript - 调用replaceWith会出现 "not a function"错误(用文本和html的混合替换文本节点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699925/