我使用jquery parseHTML加载到DOM中,然后搜索关键字,并在关键字周围放置一个带类的跨度标记,然后希望将其返回到一个字符串中并插入到主字符串中
    var mainStr = '<div>... a long html ...</div>'下面是html主字符串的一部分。我有一个位置,在经过一些修改后,我将把它重新插入到主串中。
    var str ='<span></span> Here is <a href="someurl">xxxxx </a> a presentation of certain statements';
    var myHtml = $.parseHTML(str);
   var keyword = 'presentation'.
   $.each(myHtml, function (i, el) {
   if (el.nodeName == '#text') {
      var loc = el.nodeValue.search(keyword);
   if(loc >0)
      el.nodeValue = el.nodeValue.replace(keyword, "<span class='redColor'>" + keyword + "</span>");
     });问题是如何将myHtml对象作为字符串返回,例如:
 <span></span> Here is <a href="someurl">xxxxx </a> a <span class="redColor">presentation</span> of certain statements'若要插入mainHtml字符串,请执行以下操作。
谢谢你的帮助。
发布于 2016-03-02 12:21:33
您不应该使用html内容更新文本节点的节点值,它将不会被解析。
相反,您可以用更新的html结构替换text节点,例如
var str = '<span></span> Here is <a href="someurl">xxxxx </a> a presentation of certain statements';
var keyword = 'presentation';
var myHtml = $('<div />', {
  html: str
});
myHtml.contents().contents().addBack().each(function() {
  if (this.nodeType == Node.TEXT_NODE) {
    var loc = this.nodeValue.search(keyword);
    if (loc > 0) {
      var $tmp = $('<div />', {
        html: this.nodeValue.replace(keyword, "<span class='redColor'>" + keyword + "</span>")
      })
      $(this).replaceWith($tmp.contents());
    }
  }
})
var html = myHtml.html();
$('#result').text(html);<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
https://stackoverflow.com/questions/35738358
复制相似问题