按类型和名称输入的目标(选择器)


132

我需要将某些复选框输入更改为页面上部分而非全部输入的隐藏输入。

<input type="checkbox" name="ProductCode"value="396P4"> 
<input type="checkbox" name="ProductCode"value="401P4"> 
<input type="checkbox" name="ProductCode"value="F460129">

下面的jquery代码仅按类型选择输入,这会导致所有复选框都变为隐藏的输入。是否可以将input =“ checkbox”和name =“ ProductCode”的类型都作为选择器进行检查,所以我可以专门针对这些对象我想改变吗?

$("input[type='checkbox']").each(function(){
var name = $(this).attr('name'); // grab name of original
var value = $(this).attr('value'); // grab value of original
var html = '<input type="hidden" name="'+name+'" value="'+value+'" />';
$(this).after(html).remove(); // add new, then remove original input
});

Answers:


285

您需要一个多属性选择器

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

要么

$("input:checkbox[name='ProductCode']").each(function(){ ...

最好使用CSS类来标识您要选择的类,但是由于许多现代浏览器实现了document.getElementsByClassName用于选择元素的方法,并且比按name属性选择要快得多


两者都对我有用,但是我使用了第二种方法。THX,我还有一个问题,但是我要再问一个问题。
user357034

22

您可以通过以下方式组合属性选择器:

$("[attr1=val][attr2=val]")...

因此元素必须同时满足两个条件。当然,您可以使用两个以上。另外,请勿这样做[type=checkbox]。jQuery为此提供了一个选择器,:checkbox因此最终结果是:

$("input:checkbox[name=ProductCode]")...

属性选择器很慢,因此建议的方法是在可能的地方使用ID和类选择器。您可以将标记更改为:

<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">

让您使用快选择:

$("input.ProductCode")...

显然这也可以,但是我只能给一个人正确答案的荣誉。:)一件事是我不能按班级定位,因为除非添加班级以及这样做的意义,否则我无权访问标记。但是Thx!
user357034

6
input[type='checkbox', name='ProductCode']

这就是CSS方式,我几乎可以肯定它会在jQuery中工作。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.