简体   繁体   English

如何使用jQuery对选择器的结果进行迭代

[英]how to iterate in a result of selector with jquery

i've some checkbox and i want to change background color of them when are selected more than one checkbox. 我有一些复选框,当我选择了多个复选框时,我想更改它们的背景颜色。 I'm trying from this way: 我正在尝试通过这种方式:

var checked = $("input[@type=checkbox]:checked");
$('tr[name="' + checked.attr('name') + '"]').each(function() {
                        $(this).css('background-color', '#0000DD');
                    });

only the first selected changes is color and the other selected no, can you help me? 只有第一个选择的更改是颜色,其他选择的不是,您能帮我吗? does selector give in output only the first? 选择器只给出第一个输出吗?

SOLVED IN THIS WAY: 通过以下方式解决:

$("input[type=checkbox]:checked").parents('tr').css('background-color', '#0000DD');

jQuery is not XPath. jQuery不是XPath。 Omit the @ . 省略@ Also, the .css method applies the style to all elements ib the collection, so you can omit .each . 同样, .css方法将样式应用于集合中的所有元素,因此您可以省略.each

var checked = $("input[type=checkbox]:checked");
$('tr[name="' + checked.attr('name') + '"]').css('background-color', '#0000DD');

Edit: I think that you misunderstand the method logic. 编辑:我认为您误解了方法的逻辑。
If you want to change the style of the container <tr> element, you have to loop through every element in the checkbox collection, and run some code on it: 如果要更改容器<tr>元素的样式,则必须遍历checkbox集合中的每个元素,并在其上运行一些代码:

$("input[type=checkbox]:checked").each(function() {
    $(this).closest('tr').css('background-color', '#0000DD');
});

.attr will only return the attribute of the first matched element. .attr将仅返回第一个匹配元素的属性。 You have to traverse the result of the first selector (and also select the attribute without an @): 您必须遍历第一个选择器的结果(并且还选择不带@的属性):

var checked = $("input[type=checkbox]:checked").each(function() {
    $('tr[name="' + $(this).attr('name') + '"]').css('background-color', '#0000DD');
});

Replace [@type=checkbox] by [type=checkbox] or just ':checkbox`. [@type=checkbox]替换为[type=checkbox]或仅使用':checkbox`。 Try this. 尝试这个。

$("input:checkbox:checked").each(function(){
     $('tr[name="' + this.name + '"]').each(function() {
          $(this).css('background-color', '#0000DD');
     });
});

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

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