jQuery - 通过“名称”选择一个元素属性

发布于 2024-10-12 07:48:41 字数 232 浏览 2 评论 0原文

我知道你可以使用 [name] 来做到这一点,但问题是我的输入名称属性包含方括号 [] :(

var thename = 'blah[blah][]'; // <- this value is dynamic
$("*[name='"+thename+"']").each()...

还有其他方法可以选择这个名称字段的元素?

I know you can do this with [name] but the problem is that my input name attribute contains square brackets [] inside :(

var thename = 'blah[blah][]'; // <- this value is dynamic
$("*[name='"+thename+"']").each()...

Is there any other method I could select this element by the name field?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

没有心的人 2024-10-19 07:48:41

你必须转义它们,你可以使用正则表达式替换来做到这一点

var thename = 'blah[blah][]'; // <- this value is dynamic
$("*[name='"+thename.replace(/\[/g, '\\\\[').replace(/\]/g, '\\\\]')+"']").each()...

或者创建一个函数

function esc(a) { return a.replace(/\[/g, '\\\\[').replace(/\]/g, '\\\\]'); }
var thename = 'blah[blah][]'; // <- this value is dynamic
$("*[name='"+esc(thename)+"']").each()...

You have to escape them, you can do this with a regex replace

var thename = 'blah[blah][]'; // <- this value is dynamic
$("*[name='"+thename.replace(/\[/g, '\\\\[').replace(/\]/g, '\\\\]')+"']").each()...

Or to make a function

function esc(a) { return a.replace(/\[/g, '\\\\[').replace(/\]/g, '\\\\]'); }
var thename = 'blah[blah][]'; // <- this value is dynamic
$("*[name='"+esc(thename)+"']").each()...
北方的巷 2024-10-19 07:48:41
If you wish to use any of the meta-characters 
( such as !"#$%&'()*+,./:;?@[\]^`{|}~ ) as a 
literal part of a name, you must escape the 
character with two backslashes: \\. 
For example, if you have an an element with 
id="foo.bar", you can use the selector $("#foo\\.bar"). 

引用自 http://api.jquery.com/category/selectors/

If you wish to use any of the meta-characters 
( such as !"#$%&'()*+,./:;?@[\]^`{|}~ ) as a 
literal part of a name, you must escape the 
character with two backslashes: \\. 
For example, if you have an an element with 
id="foo.bar", you can use the selector $("#foo\\.bar"). 

quoted from http://api.jquery.com/category/selectors/

﹉夏雨初晴づ 2024-10-19 07:48:41

首先尝试在属性选择器中使用双引号:

$('*[name="'+thename+'"]').each()...

如果这不起作用,您可以使用 .filter() 方法,利用直接 DOM 访问:

$('input').filter(function() {
    return this.name == thename;
})...

First try using double quotes within the attribute selector:

$('*[name="'+thename+'"]').each()...

If that doesn't work, you can use the .filter() method, taking advantage of direct DOM access:

$('input').filter(function() {
    return this.name == thename;
})...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文