[英]I want to find an input element closest a span when I click the span, can you help me?
I want to find an input element closest a span when i click the span当我单击跨度时,我想找到最接近跨度的输入元素
HTML HTML
<div>
<span class="text"></span>
<input type="text" name="an_element_name">
</div>
<div>
<span class="text"></span>
<input type="text" name="an_element_name">
</div>
JQuery查询
$('.text').click(function(e){
let text = $(e.target),
input = text.closest('input[name=an_element_name]').find('input[name=an_element_name]');
input.val('some value');
});
but, I'm still can't set a value of the input.但是,我仍然无法设置输入值。 Can you help me ?
你能帮助我吗 ?
You need to use text.next('input[name=an_element_name]');
您需要使用
text.next('input[name=an_element_name]');
since the .closest()
is looking for an ancestor of your span, not siblings.因为
.closest()
正在寻找您的跨度的祖先,而不是兄弟姐妹。
.closest()
= Goes up the html tree and search for the element. .closest()
= 向上 html 树搜索元素。.next()
= Searches for an element after the current element. .next()
= 在当前元素之后搜索一个元素。.find()
= Searches for children of the given element. .find()
= 搜索给定元素的子元素。 Demo演示
$('.text').click(function(e){ let text = $(e.target), input = text.next('input[name=an_element_name]'); input.val('some value'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="text">click</span> <input type="text" name="an_element_name">
You are using closest() incorrectly, you should use next() instead.您错误地使用了nearest() ,您应该使用next()来代替。
next(): Get the immediately following sibling of each element in the set of matched elements.
next():获取匹配元素集中每个元素的紧跟其后的兄弟元素。 If a selector is provided, it retrieves the next sibling only if it matches that selector.
如果提供了选择器,则仅当它与该选择器匹配时才检索下一个兄弟。
You can achieve it in this simple way您可以通过这种简单的方式实现它
$('.text').click(function(e){ let text = $(e.target), input = text.next('input[name=an_element_name]'); input.val('some value'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="text">Click me</span> <input type="text" name="an_element_name">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.