我正在尝试在整个页面中搜索大约 20 多个单词。如果存在任何单词,我希望并提醒与找到的单词一起出现。我已经做到了这一点:
if ($("body").has(":contains('Stunning')").length) {
alert("Stunning");
}
但我需要指定多个单词,并让警报显示找到的特定单词。
任何帮助表示赞赏。
$.each(['iste','quia','birds','words'],function(index, value){
var present = $("body:contains('"+value+"')").length;
if(present){
alert(value);
}
});
这是一个工作小提琴。 http://jsfiddle.net/DNKdm/
编辑:http: //jsfiddle.net/k7aEV/2/
var searchText = getPageText(),
wordlist = ['Sed','Neque','birds','words'];
//Based on solution found at
//http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery
function getTextNodesIn(node, includeWhitespaceNodes) {
var textNodes = [], whitespace = /^\s*$/;
function getTextNodes(node) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || !whitespace.test(node.nodeValue)) {
textNodes.push(node.nodeValue);
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
getTextNodes(node.childNodes[i]);
}
}
}
getTextNodes(node);
return textNodes;
}
function getPageText (){
var el = document.getElementById('wrapper'), //Replace with body or content wrapper div.
pageTxt = getTextNodesIn(el).join(' ').replace(/[^\w ]/g," ").toLowerCase()+" ";
return pageTxt;
}
$.each(wordlist,function(index, value){
var found = searchText.indexOf(value.toLowerCase()+" "); //remove the space if you don't want whole words only.
if(found !== -1){
alert('Found: '+value);
}
});