[英]jquery click the highest parent input's child
I am trying to click the first input checkbox when I click the second one. 当我点击第二个输入时,我试图点击第一个输入复选框。
<li>
<div>
<input type='checkbox' value='x'/>
</div>
<ul>
<li>
<ul>
<li>
<div>
<input type='checkbox' id='check' value='b'/>
</div>
</li>
</ul>
</li>
</ul>
</li>
doing this does not help: 这样做没有帮助:
$('#check').click(function(){
$('this').parents('li #parent').children('div').find('input').click();
});
what am I missing here? 我在这里想念的是什么?
$('#check').click(function(){
$('#parent').find('input').first().click();
});
if you use parent
as class 如果你使用parent
类作为类
<li class='parent'>
Then you can do this - 然后你可以这样做 -
$('#check').click(function(){
$(this).closest('.parent').find('input').first().click();
});
Since id is unique there is no need to look for any parents, you can directly use the id
由于id是唯一的,不需要寻找任何父母,你可以直接使用id
$('#check').click(function(){
$(this).closest('li[id]').find('input').first().click();
});
Give the first checkbox its own ID. 给第一个复选框提供自己的ID。 Then you can use 然后你可以使用
$('#firstcheck').prop('checked',true);
I'd suggest, given that the id
is dynamically generated: 我建议,鉴于id
是动态生成的:
$('#check').click(function(){
$(this).closest('div[id]').find('input').first().click();
});
If, as you note in comments to other answers, the id
for #check
is also dynamic I'd strongly suggest adding a consistent class-name to the input
-element in order to bind the click()
event-handler. 如果您在评论其他答案注意, id
为#check
也是动态的我强烈建议增加一个一致的类名的input
,以绑定-元素click()
事件处理程序。 Otherwise you'll end up having to check the 'depth', or the number of ancestors, in order to decide which should be clicked, and which should trigger the click event-handler. 否则,你会最终不得不检查“深度”,或祖先的数量,以决定哪些应该被点击,并应触发 click事件处理程序。
This will work without an ID, but as David Thomas mentioned, it's more efficient to use an ID. 这将在没有ID的情况下工作,但正如David Thomas所提到的,使用ID更有效。
$('#check').click(function(){
$(this).parents('li').last().find('div:first input').click();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.