繁体   English   中英

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

[英]jQuery - select a element by the “name” attribute

我知道您可以使用[name]来执行此操作,但问题是我的输入名称属性在:(内包含方括号[]

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

我还有其他方法可以通过名称字段选择此元素吗?

您必须转义它们,您可以使用正则表达式替换

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()...
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/

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

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

如果那不起作用,则可以使用.filter()方法,利用直接DOM访问的优势:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM