Javascript 用于名称属性中带有方括号的输入的 jQuery 选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2364982/
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 selector for inputs with square brackets in the name attribute
提问by aidan
I'm trying to select this element which has square brackets in the name attribute:
我试图选择这个在 name 属性中有方括号的元素:
<input type="text" name="inputName[]" value="someValue">
I've tried this (which doesn't work):
我试过这个(这不起作用):
$('input[inputName[]=someValue]')
and neither does this:
这也不是:
$('input[inputName[]=someValue]')
or this:
或这个:
$('input["inputName[]"=someValue]')
EDIT:As some of you have pointed out, $('input[inputName=someValue]')would never work. What I was trying to do was: $('input[name=inputName][value=someValue]'). (But with []in the name attribute).
编辑:正如你们中的一些人指出的那样,$('input[inputName=someValue]')永远不会工作。我试图做的是:$('input[name=inputName][value=someValue]')。(但[]在 name 属性中)。
回答by Dancrumb
Per the jQuery documentation, try this:
根据jQuery 文档,试试这个:
$('input[inputName\[\]=someValue]')
[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:
[编辑] 但是,我不确定这是否适合您的选择器的语法。你可能想要:
$('input[name="inputName[]"][value="someValue"]')
回答by Pointy
You can use backslash to quote "funny" characters in your jQuery selectors:
您可以使用反斜杠在 jQuery 选择器中引用“有趣”的字符:
$('#input\[23\]')
For attribute values, you can use quotes:
对于属性值,您可以使用引号:
$('input[name="weirdName[23]"]')
Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?
现在,我对你的例子有点困惑;你的 HTML 到底是什么样子的?字符串“inputName”出现在哪里,特别是?
editfixed bogosity; thanks @Dancrumb
编辑固定的笨重;谢谢@Dancrumb
回答by Gumbo
The attribute selector syntax is [name=value]where nameis the attribute name and valueis the attribute value.
属性选择器语法是[name=value]wherename是属性名称,value是属性值。
So if you want to select all inputelements with the attribute namehaving the value inputName[]:
因此,如果要选择input属性name值为 的所有元素inputName[]:
$('input[name="inputName[]"]')
And if you want to check for two attributes (here: nameand value):
如果你想检查两个属性(这里:name和value):
$('input[name="inputName[]"][value=someValue]')
回答by Eric Kigathi
If the selector is contained within a variable, the code below may be helpful:
如果选择器包含在变量中,下面的代码可能会有所帮助:
selector_name = $this.attr('name');
//selector_name = users[0][first:name]
escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\');
//escaped_selector_name = users\[0\]\[first\:name\]
In this case we prefix all special characters with double backslash.
在这种情况下,我们用双反斜杠作为所有特殊字符的前缀。
回答by slva2000
Just separate it with different quotes:
只需用不同的引号将其分开:
<input name="myName[1][data]" value="myValue">
JQuery:
查询:
var value = $('input[name="myName[1][data]"]').val();

