Javascript jQuery .search() 到任何字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1854493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery .search() to any string
提问by Omar
I saw this code snippet:
我看到了这个代码片段:
$("ul li").text().search(new RegExp("sometext", "i"));
and wanted to know if this can be extended to any string?
并想知道这是否可以扩展到任何字符串?
I want to accomplish the following, but it dosen't work:
我想完成以下操作,但它不起作用:
$("li").attr("title").search(new RegExp("sometext", "i"));
Also, anyone have a link to the jQuery documentation for this function? I fail at googling apparently.
另外,有人有这个函数的 jQuery 文档的链接吗?我显然不擅长谷歌搜索。
回答by Jacob Relkin
search()is a String method.
search()是一个字符串方法。
You are executing the attrfunction on every<li>element.
You need to invoke eachand use the thisreference within.
您正在每个元素attr上执行该函数。您需要调用并使用其中的引用。<li>eachthis
Example:
例子:
$('li').each(function() {
var isFound = $(this).attr('title').search(/string/i);
//do something based on isFound...
});
回答by Biswajit Roy
if (str.toLowerCase().indexOf("yes") >= 0)
Or,
或者,
if (/yes/i.test(str))
回答by Chuck Vose
Ah, that would be because RegExp is not jQuery. :)
啊,那是因为 RegExp 不是 jQuery。:)
Try this page. jQuery.attrdoesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text()to return the String representation.
试试这个页面。jQuery.attr不返回字符串,因此肯定会导致这方面的问题。幸运的是,我相信您可以只使用.text()来返回 String 表示。
Something like:
就像是:
$("li").val("title").search(/sometext/i));

