JS/Jquery,匹配未找到 PNG = match('/gif|jpg|jpeg|png/')
我有以下代码,用于匹配 fancybox 可能的元素:
$('a.grouped_elements').each(function(){
var elem = $(this);
// Convert everything to lower case to match smart
if(elem.attr('href').toLowerCase().match('/gif|jpg|jpeg|png/') != null) {
elem.fancybox();
}
});
它与 JPG 配合得很好,但由于某种原因与 PNG 不匹配。有人看到代码有错误吗? 谢谢
I have the following code which I use to match fancybox possible elements:
$('a.grouped_elements').each(function(){
var elem = $(this);
// Convert everything to lower case to match smart
if(elem.attr('href').toLowerCase().match('/gif|jpg|jpeg|png/') != null) {
elem.fancybox();
}
});
It works great with JPGs but it isn't matching PNGs for some reason. Anyone see a bug with the code?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有几件事。
Match 接受
RegExp
对象,而不是字符串。它可能在某些浏览器中工作,但绝对不是标准的。没有字符串
另外,您可能希望在文件名的末尾而不是字符串中的任何位置检查这些字符串。
只在带有 $ 后缀的字符串末尾搜索
不需要将 href 设置为小写,只需执行不区分大小写的搜索
/i
即可。在图像扩展名之前查找一个点作为附加检查。
还有一些测试。 我不知道您如何使用
.匹配
。你用的是什么浏览器?A couple of things.
Match accepts an object of
RegExp
, not a string. It may work in some browsers, but is definitely not standard.Without the strings
Also, you would want to check these at the end of a filename, instead of anywhere in the string.
Only searching at the end of string with $ suffix
No need to make href lowercase, just do a case insensitive search
/i
.Look for a dot before the image extension as an additional check.
And some tests. I don't know how you got any results back with using a string argument to
.match
. What browser are you on?我猜它会匹配字符串中的任何位置(它将匹配“http://www.giftshop.com /”例如)可以被视为一个错误。我会用
I guess the fact that it'll match anywhere in the string (it would match "http://www.giftshop.com/" for instance) could be considered a bug. I'd use
您将字符串而不是正则表达式传递给 match() 函数。在 JavaScript 中,字符串用单引号分隔,正则表达式用正斜杠分隔。如果您同时使用两者,您将得到一个字符串,而不是正则表达式。
You are passing a string to the match() function rather than a regular expression. In JavaScript, strings are delimited with single quotes, and regular expressions are delimited with forward slashes. If you use both, you have a string, not a regex.
这对我来说非常有效:
/.+\.(gif|png|jpe?g)$/i
.+
->任何字符串\.
->接下来是一个点。(gif|png|jpe?g)
->然后是任何这些扩展名。 jpeg 可能有也可能没有字母 e。$
->现在字符串的结尾是预期的/i
->不区分大小写模式:同时匹配sflkj.JPG
和lkjfsl.jpg
This worked perfectly for me:
/.+\.(gif|png|jpe?g)$/i
.+
-> any string\.
-> followed by a point.(gif|png|jpe?g)
-> and then followed by any of these extensions. jpeg may or may not have the letter e.$
-> now the end of the string it's expected/i
-> case insensitive mode: matches bothsflkj.JPG
andlkjfsl.jpg