1

ページ全体で約 20 個以上の単語を検索しようとしています。いずれかの単語が存在する場合は、見つかった単語と共に表示されるように警告します。私はこれまでのところ持っています:

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

ただし、複数の単語を指定し、見つかった特定の単語をアラートに表示させる必要があります。

どんな助けでも大歓迎です。

4

1 に答える 1

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);
    }
});
于 2013-08-13T01:58:10.997 に答える