为什么这个 JavaScript 正则表达式不起作用?
由于某种原因,这不起作用,但我所有的搜索都表明它应该起作用。
我在一个元素上有一个 id,我试图将值增加 1。
所以假设我
<input id="someText1">
想将 1 更改为 2,所以我最终
<input id="someText2">
尝试使用以下命令仅匹配文本
text = $("input").attr("id").match(/^[a-zA-Z]+$/);
但是当我输出文本的值,我得到 null
请帮助!
For some reason this is not working, yet all my searches say it should work.
I have an id on an element where I am trying to increment the value by 1.
so let's say I have
<input id="someText1">
I want to change the 1 to a 2, so I end up with
<input id="someText2">
I've tried to match just the text using
text = $("input").attr("id").match(/^[a-zA-Z]+$/);
But when I output the value of text, I get null
Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
删除
$
符号(文本确实以数字结尾,而您告诉它它以字母结尾)Remove the
$
sign (the text does end with a number and you're telling it that it ends with a letter)你的正则表达式应该是
Are you after this?
Your regular expression should be
Are you after this?
match
选择器必须与 ID 完全相同,并且由于您的正则表达式匹配仅包含 az 和 AZ 的任何字符串,因此它与someText1
不匹配!你应该尝试The
match
selector must equal the ID exactly, and as your regex matches any string containing ONLY a-z and A-Z, it doesn't matchsomeText1
! You should try我建议使用类名选择器,例如
$('.inputs')
因为它比获取页面上的所有输入元素然后按 id 过滤(尤其是在现代浏览器中)要快)。I would suggest using a class name selector, such as
$('.inputs')
as it will be faster than getting all the input elements on the page and then filtering by id (esp. in modern browsers).