Javascript 循环浏览HTML文档中的所有单词,如果单词符合特定条件,则向该单词添加一个类
我想循环浏览HTML文档中的所有单词,如果单词是阿拉伯语单词,则在单词中添加一个span。你知道如何在jQuery中实现这一点吗 我尝试了以下方法:Javascript 循环浏览HTML文档中的所有单词,如果单词符合特定条件,则向该单词添加一个类,javascript,jquery,arabic,Javascript,Jquery,Arabic,我想循环浏览HTML文档中的所有单词,如果单词是阿拉伯语单词,则在单词中添加一个span。你知道如何在jQuery中实现这一点吗 我尝试了以下方法: var text = $('body').text().split(' '); for( var i = 0, len=text.length; i<len; i++ ) { var mytext = $(this).val(); var arabic = /[\u06
var text = $('body').text().split(' ');
for( var i = 0, len=text.length; i<len; i++ ) {
var mytext = $(this).val();
var arabic = /[\u0600-\u06FF]/;
if(arabic.test(mytext)){
text[i] = '<span class="arabic">' + text[i] + '</span>';
}
}
$(this).html(text.join(' '));
}
var text=$('body').text().split(“”);
对于(var i=0,len=text.length;i您需要在低于jQuery通常用于:text节点的级别上执行此操作
此HTML:
<p>Hi there</p>
到
只有大约三行更改。运行此操作时会发生什么?您可能对
<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;
}
}