jquery找到单词并提醒它

时间:2013-08-13 01:54:22

标签: jquery alert

我正在尝试搜索整个页面大约20多个单词。如果我想要的任何单词存在,并警告显示找到的单词。我到目前为止:

if ($("body").has(":contains('Stunning')").length) { 
alert("Stunning");
}

但我需要指定多个单词,并让警报显示找到的特定单词。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

$.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);
    }
});