2015-11-13 87 views
0

的混合文本节点我有,我想用HTML来取代它的一些文本的文本节点:的jQuery:替换文本和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 
    }); 

trying to replace on any element. i am trying with x[0] 

rep = x[0].data.replace(//\"id\": \"(.*)\",/, "/\"id\": \"<a href=\"https:example.com/\$1\">$1</a>\"") 

然后尝试

x[0].replaceWith(rep) 

它说,X [0] .replaceWith不是一个函数

因此,如何替换HTML元素的文本?

回答

0

我试了下面的工作。使用$(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. 
})