如果页面上存在字符串,则执行功能

时间:2014-05-14 12:25:55

标签: javascript jquery

我只是希望有一个警告说" Page包含字符串"如果页面上存在特定字符串。

不应该这么简单:

if ('*:contains("This String")') {
    alert('Page Contains String');
}

4 个答案:

答案 0 :(得分:7)

Native JS:

if(document.body.innerText.indexOf("This String") !== -1){
    // Do stuff
}

但您可能希望使用document.body.textContent。取决于您想要/需要支持的浏览器。 (IE 8或更低版本不支持textContent。)

为获得最大兼容性,请尝试以下操作:

var text = document.body.innerText || document.body.textContent;
if(text.indexOf("This String") !== -1){
    //Do stuff
}

答案 1 :(得分:3)

使用jQuery的另一种方法 -

if( $('body:contains(string)').length ) {
    console.log('found it');
};

你的语法有些混乱,但是你走的是正确的道路。

if ( $('*:contains("This String")').length ) { // you needed an alias to jQuery, some proper parentheses and you must test for length
    alert('Page Contains String');
}

此处可测试 - http://jsfiddle.net/jayblanchard/zg75Z/

答案 2 :(得分:2)

尝试这种方式:

if($("body").text().indexOf("This String") > -1) {
    alert("page contains string");
}

或纯粹的JS:

if (~document.body.textContent.indexOf('This String')) {
    alert("page contains string");
}

答案 3 :(得分:2)

创建一个html的字符串

//Retrieves html string
var htmlString = $('body').html();

indexOf()方法返回字符串中第一次出现指定值的位置。如果要搜索的值永远不会发生,则此方法返回-1

var index = htmlString.indexOf("this string");

if (index != -1)
    alert("contains string");

<强>单行

if($('body').html().indexOf("this string") !== -1)
     alert("contains string")