当多个选择器在jQuery中执行时调用每个项目
问题描述:
我想将每个复选框的.parent("span").prop("title")
设置为它们的.parent("span").parent("td").parent("tr")
的标题。由于jQuery在存在多个元素时会迭代执行,所以我不能在没有循环的情况下做这样的事情吗?当多个选择器在jQuery中执行时调用每个项目
$(":checkbox").parent("span").parent("td").parent("tr").prop("title", $(this).parent("span").prop("title"));
在浏览器中呈现这样的东西。
<tr class="GridRow_Default" id="ctl00_body_grdTime_ctl00__2">
<td align="center">
<span title="Regularizable">
<input id="ctl00_body_grdTime_ctl00_ctl07_chkSub" type="checkbox" name="ctl00$body$grdTime$ctl00$ctl07$chkSub">
</span>
</td>
</tr>
答
我不能做这样的事情没有一个循环?
NO。要获取当前元素引用,您必须迭代元素。您可以使用each()
迭代所有复选框。
$(':checkbox').each(function() {
// `$(this)` here is the current checkbox
$(this)
.closest('tr') // Get closest ancestor `<tr>`
.attr('title', $(this).parent().attr('title')); // Set attribute value of `title` to that of the `parent`
});
答
使用过滤器()得到的只是与SPAN其中包含输入的TR:checkbox元素,并设置SPAN到TR的标题属性的值。
$('tr').filter(function() {
return $(this).find('span > :checkbox').length;
}).prop('title', function() { return $(this).find('span').eq(0).prop('title'); });
答
尝试使用:has()
,.prop(function(propertyName, function)
,.closest()
$("span:has(:checkbox)").prop("title", function(index, prop) {
return $(this).closest("tr").prop("title");
})
我觉得OP要做到这一点,而不使用循环。 “我不能像没有循环一样做这样的事情吗?” –
@RinoRaj是的,但这是不可能的。我已添加说明。 – Tushar
@RayonDabre从jQuery源代码,'prop'和'attr' setters使用'access()'。下面是'1.3中({ \t道具:函数(名称,值){ \t \t回访问(这一点,jQuery.prop,名称,值的arguments.length> 1); \t}'和'access'迭代元素,'var access = function(elems,fn,key,value,chainable,emptyGet,raw){...... if(fn){;我++){ \t \t \t \t FN( \t \t \t \t \t elems的[I], \t \t \t \t \t键, \t \t \t \t \t生吃?值:value.call(elems [i],i,fn(elems [i],key)) \t \t \t \t); \t \t \t} \t \t}' – Tushar