2017-06-29 64 views
1

我想获取匹配元素集合中每个元素的组合文本内容,但其中包含图像。如何获取元素中的文本,其中的图像(JQuery)?

例如,对于此输入:

<div id="test">Lorem ipsum <strong>dolor</strong> sit amet, consectetur <a href="...">adipiscing</a> elit: <img src="test.png" alt="test"/> Etiam vulputate arcu risus</div> 

我想获得这个输出:

Lorem ipsum dolor sit amet, consectetur adipiscing elit: <img src="test.png" alt="test"/> Etiam vulputate arcu risus 

怎么可能用JQuery的来管理呢?它几乎与.text()函数相同,但我应该以某种方式保留图像。

+0

这会不会是直线前进。你可能最好通过节点检索textNodes和DOMElements的outerHTML,其中tagName =='IMG'。 –

回答

3

我相信我有一个简单的解决方案。这里是你可以做什么:

var source = $("#test").clone(); //clone your dom element 
source.find(':not(img)').remove(); //remove all tags exept img 
console.log(source.html()); //Watch result in console 

UPDATE:

如果你不想删除的标签内容:

$("#test").find("*").not("img").each(function() { 
    $(this).replaceWith(this.innerHTML); 
}); 

这里是codepen

更新2:

如果您有嵌套元素:

var beginsWith = function(needle, haystack){ 
    return (haystack.substr(0, needle.length) == needle); 
}; 

var filterHTML = function($elem) { 
    var $cp = $elem.clone(); 

    var changed = true; 
    while(changed) { 
     var tx1 = $cp.html(); 
     $cp.contents().each(function() { 
      if(this.nodeType === Node.COMMENT_NODE) { 
       $(this).remove(); 
      } else if(this.nodeType == Node.ELEMENT_NODE) { 

       if(this.nodeName == 'IMG') { 

        var src = $(this).attr("src"); 

        if(
         !beginsWith("http://",src) && 
         !beginsWith("https://",src) && 
         !beginsWith("data:image",src) 
        ) { 
         $(this).remove(); 
        } 

       } else { 
        $(this).replaceWith(this.innerHTML); 
       } 

      } 

     }); 
     var tx2 = $cp.html(); 
     changed = (tx1 != tx2); 
    } 

    return $cp.html(); 

}; 
+0

谢谢。但你能解释它是如何工作的吗? '.remove()'不仅应该删除元素本身,而且应该删除它里面的所有内容 –

+0

@IterAtor ok,现在我得到你想要的东西。这是更新中的另一个解决方案 –

1

在对方的回答,如果你发现它会删除所有的元素标签除的img因此,强元素中的文本( dolor)和锚点元素(adipiscing)将不会显示,请使用此代码,以便您获得预期的输出。

<div id="test">Lorem ipsum <strong>dolor</strong> sit amet, consectetur <a href="...">adipiscing</a> elit: <img src="test.png" alt="test"/> Etiam vulputate arcu risus</div> 
<script> 
$(function(){ 
var $contents = $('#test').contents(); 
var returnString=''; 
for(var i=0;i< $('#test').contents().length; i++){ 
if($contents[i].nodeType == 3) 
    returnString = returnString + $contents[i].textContent; 
else if($contents[i].nodeType != 3 && $contents[i].nodeName != 'IMG') 
    returnString = returnString + $contents[i].innerHTML; 
else 
    returnString = returnString + $contents[i].outerHTML; 
} 
console.log(returnString); 
}); 
</script> 

工作小提琴:https://jsfiddle.net/6h924n28/

输出:Lorem存有悲坐阿梅德,consectetur adipiscing ELIT:img标签Etiam vulputate arcu risus

相关问题