您需要在通常使用jQuery的級別以下的級別執行此操作:Text節點。
此HTML:
<p>Hi there</p>
產生含有一個單一的文本節點的p
元件。通常,對於jQuery,您只能使用元素,但要以非破壞性方式執行您所做的操作(不刪除並重新創建將解除其所有事件處理程序的所有元素),則需要使用節點級別像DOM的splitText
和insertBefore
方法。
這是不復雜,但它只是意味着在不同的水平上工作。
My other answer here on Stack Overflow向您展示瞭如何遍歷文檔的文本節點,找到它們中的文本,將它們分開並放入包裝元素中(在您的情況下,爲span
)。在這種情況下,代碼使用簡單的正則表達式來查找看起來像鏈接並使其成爲實際鏈接的文本。改變:
<p>I found this information at http://stackoverflow.com.</p>
到
<p>I found this information at <a href="http://stackoverflow.com">http://stackoverflow.com</a>.</p>
你可以看到這是非常,非常類似於你想要做什麼。你基本上只是改變你想要找到文本的方式,其餘的代碼已經完成了這項工作。
下面是這個問題的答案更新爲使用一個詞在你所報阿拉伯字符的範圍內的正則表達式查找任何字符代碼:
// The regex matches a series of characters in the given range.
// (Double-check this, I believe there's a second Arabic range in
// the Unicode standard, but I know next to nothing about Arabic.)
walk(document.body, /[\u0600-\u06FF]+/);
function walk(node, targetRe) {
var child;
switch (node.nodeType) {
case 1: // Element
for (child = node.firstChild;
child;
child = child.nextSibling) {
walk(child, targetRe);
}
break;
case 3: // Text node
handleText(node, targetRe);
break;
}
}
function handleText(node, targetRe) {
var match, targetNode, followingNode, wrapper;
// Does the text contain our target string?
match = targetRe.exec(node.nodeValue);
if (match) {
// Split at the beginning of the match
targetNode = node.splitText(match.index);
// Split at the end of the match.
// match[0] is the full text that was matched.
followingNode = targetNode.splitText(match[0].length);
// Wrap the target in an `span` element with an `arabic` class.
// First we create the wrapper and insert it in front
// of the target text. We use the first capture group
// as the `href`.
wrapper = document.createElement('span');
wrapper.className = "arabic";
targetNode.parentNode.insertBefore(wrapper, targetNode);
// Now we move the target text inside it
wrapper.appendChild(targetNode);
// Clean up any empty nodes (in case the target text
// was at the beginning or end of a text node)
if (node.nodeValue.length == 0) {
node.parentNode.removeChild(node);
}
if (followingNode.nodeValue.length == 0) {
followingNode.parentNode.removeChild(followingNode);
}
// Continue with the next match in the node, if any
match = followingNode
? targetRe.exec(followingNode.nodeValue)
: null;
}
}
只有大約三線改變。
當你運行這個時會發生什麼? – Dolchio
您可能感興趣的[Lettering.js](http://letteringjs.com/) – Pointy