[英]Jquery closest() doesn't work on elements within different div
I'm trying to use closest()
to get <input>
element which is in different div. 我正在尝试使用
closest()
获取不同div中的<input>
元素。 Here's the markup: 这是标记:
<div class="row">
<div class="span8">
<input type="text" disabled="disabled" id="image-name">
</div>
<div class="span4">
<input type="file">
</div>
</div>
Here's the script 这是剧本
$(document).ready(function(){
$("input:file").change(function (){
var fileName = $(this).val();
//Put the file name inside the disabled <input>
$(this).closest('input:disabled').val(fileName);
});
});
It doesn't do anything though. 它什么也没做。 I tried changing
input:disabled
to #image-name
but still doesn't work. 我尝试将
input:disabled
更改为#image-name
但仍然无法正常工作。
Any solution? 有什么办法吗?
Thanks 谢谢
If you have an id on the other INPUT element, why are you using the closest function? 如果在另一个INPUT元素上有一个ID,为什么要使用最接近的函数? Why not just $('#image-name')?
为什么不只是$('#image-name')? The closest method does not work the way you think.
最接近的方法不符合您的想法。 closest always goes up the DOM tree until it finds a match.
最接近的总是在DOM树上向上移动,直到找到匹配项。
Based on the comment to my initial suggestion, you could get DRY by using the more fancy versions of the jQuery event binders: 根据我最初建议的评论,您可以通过使用更高级的jQuery事件绑定程序来获得DRY:
function handler(e, args) {
$(e.data.elem).val(fileName);
}
$('input:file').bind('change', { elem: '#image-name' }, handler);
$('#other-input').bind('change', { elem: '#other-field' }, handler);
reusable event handler parameterized using event data constructs. 使用事件数据构造参数化的可重用事件处理程序。
Because closest
travels upwards, not sideways. 因为
closest
向上移动,而不是侧向移动。 Just to add, it starts matching the current element as well. 只是添加,它也开始匹配当前元素。
A more generic way is to use closest
to find the common ancestor, which is .row
, and find
the disabled text box from there. 一种更通用的方法是使用
closest
来查找公共祖先,即.row
,然后从那里find
禁用的文本框。 You could also do parent
, prev
and children
, assuming the HTML is always that way. 假设HTML始终是这种方式,您也可以做
parent
, prev
和children
。
You can use: 您可以使用:
$(this).closest('.row').find('input:disabled').val(fileName);
since closest()
will traverse up through its ancestors in the DOM tree. 因为
closest()
将遍历其在DOM树中的祖先。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.