使用此 HTML:
<h1>This is my <img src="https://dummyimage.com/100x50/000/fff&text=BIG" alt="BIG"> title</h1>
在 Chrome 或 Firefox 中,如果我選擇渲染的文本并復制它(Ctrl-C),我會得到
This is my BIG title(alt圖片的文字包含在復制的文字中)
我可以使用 jQuery 實作相同的目標嗎? $('h1').text()只給我This is my title(沒有BIG)。
我知道我可以獲取alt文本本身,$('h1').attr('alt')但是如何將它插入到.text()字串中的正確位置?
uj5u.com熱心網友回復:
基本上我傳遞指定元素的所有節點(不是元素)。如果 type=3 則為文本。否則我假設它是一個影像并獲取alt屬性。例如,如果元素是,也可以進行遞回div。更新:使其遞回。
var h1 = document.querySelector("h1");
var h2 = document.querySelector("h2");
console.log(do_elem(h1));
console.log(do_elem(h2));
function do_elem(elem) {
var nodes = textNodesUnder(elem);
return nodes.join("");
}
function textNodesUnder(node) {
var all = [];
for (node = node.firstChild; node; node = node.nextSibling) {
if (node.nodeType == 3) {
all.push(node.nodeValue);
} else {
if (node.tagName == 'IMG') {
all = all.concat(node.getAttribute("alt"));
} else {
all = all.concat(do_elem(node))
}
}
}
return all;
}
<h1>This is my <img src="https://dummyimage.com/100x50/000/fff&text=BIG" alt="BIG"> title</h1>
<h2>This is <span> another <img src="https://dummyimage.com/100x50/000/fff&text=BIG" alt="BIG"> example</span> of recursion</h2>
uj5u.com熱心網友回復:
快速而骯臟的方法是獲取每個影像并在其之前或之后插入文本,然后在 .text() 呼叫之后反轉
$("img").each(function() {
if (this.getAttribute("alt")) {
this.parentNode.insertBefore(document.createTextNode(this.getAttribute("alt"), this);
}
});
您可以嘗試將創建的文本節點保存在 JQuery 或其他物件中,以便在您的文本呼叫之后將它們全部洗掉。或者,您可以再次遍歷您的 imgs 并執行
parent.removeChild(img.previousNode);
uj5u.com熱心網友回復:
您可以使用 jQuery 方法嘗試類似的操作。
/*Using jQuery clone() to avoid manipualting the DOM*/
const h1 = $('h1').clone();
//Define the alt text value
const imgAlt = h1.find('img').attr('alt');
//Define the img node inside of the h1 element
const h1Img = h1.find('img');
//Use jQuery replace with method to replace the img node with the previously defined alt text
h1Img.replaceWith(imgAlt);
//Define the text inside the string
const text = h1.text();
console.log(text)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>This is my <img src="https://dummyimage.com/100x50/000/fff&text=BIG" alt="BIG"> title</h1>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/506407.html
標籤:javascript jQuery
上一篇:用beginWithCompletionHandler替換NSOpenPanelrunModalForDirectory:的問題:
