javascript - 调用replaceWith会出现 "not a function"错误(用文本和html的混合替换文本节点)

标签 javascript jquery html

我有多个文本节点,我想用 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/

相关文章:

jQuery Validate - 从选择中获取值并根据该值将文本输入必填字段

javascript - HTML 代码中的错误

javascript - 托管 javascript 库的 CDN(即 CodeMirror)

javascript - 有没有办法设置 SegmentPoints 和 Handles 的样式?

javascript - 在 PhantomJS 中使用 Jasmine 测试 $interval

jquery - 更改 HTML onclick 事件操作(不同)

javascript - 如何在angularjs中的提交功能上获取ng-repeat复选框值

jQuery 自动完成类,如何获取 id

javascript - 根据 HTML 字符串查找 DOM 元素

javascript - 在悬停时更改图像后将图像更改回原始图像?