下一个最近的元素jQuery
HTML:下一个最近的元素jQuery,jquery,html,Jquery,Html,HTML: <a class="button">Button</a> <input type="submit" /> <a class="button">Button</a> <div> <!-- The input there can be into an another `div`, etc .. --> <input type="submit" /> </div> 按钮
<a class="button">Button</a>
<input type="submit" />
<a class="button">Button</a>
<div>
<!-- The input there can be into an another `div`, etc .. -->
<input type="submit" />
</div>
按钮
按钮
当我点击带有class
按钮的链接时
我如何定位下一个最近的输入[type=submit]
?我刚刚想到的一个方法实际上相当简单,但需要知道包含所有
和
的顶级父级,或者向输入添加一个类
您只创建了所涉及的
和type=submit
的集合
单击一个
时,您可以使用它在上一个集合中的索引来过滤掉它的索引之后的所有输入,并获取第一个
var $buttons = $('#mainContainer').find('a.button, input[type=submit]');
$('#mainContainer a.button').click(function(){
var index = $buttons.index(this);
var $input = $buttons.filter('input:gt(' + index +')').first();
});
我们需要遍历DOM以找到类型为submit的元素。在下面的代码中-我以下面的方式进行检查
是当前元素的类型submit。如果是-则结束循环并返回当前元素
查找当前元素的任何子元素
寻找下一个兄弟姐妹和他们的孩子
寻找父母、兄弟姐妹和他们的孩子
我们将为每个元素递归调用函数,直到找到我们要查找的内容
function findButton(ctrl, skipChildren) {
var controlToReturn = null;
if ($(ctrl).prop('type') === 'submit') {
controlToReturn = $(ctrl);
} else {
//We need to skip children in case the call is coming from the child (else we will be stuck in infinite loop)
if(!skipChildren){
$(ctrl).children().each(function () {
controlToReturn = findButton($(this));
if (controlToReturn != null) {
return false; //break
}
});
}
if (controlToReturn === null || controlToReturn === undefined) {
//Loop through the next siblings
$(ctrl).nextAll().each(function () {
controlToReturn = findButton($(this));
if (controlToReturn != null) {
return false; //break
}
});
}
if (controlToReturn === null || controlToReturn === undefined) {
//Go to parent and find the element in parents siblings. Note we are passing true as second parameter of this function.
$(ctrl).parents().each(function(){
controlToReturn = findButton($(this), true);
if (controlToReturn != null) {
return false; //break
}
});
}
}
return controlToReturn;
}
请参见链接中的一个工作示例。如果您包装重复组件的组,以便根据包装容器内的搜索对遍历进行更本地化,那么会简单得多。为什么?jQuery不能做我真正想做的事?当然可以。。。但是需要比组织dom更复杂的搜索。我正在为一些东西编写一个jQuery插件,但我无法真正控制HTML标记。好的。。那条信息也会有帮助的。这是否意味着你可能不知道按钮在哪里?它们是否可以索引(始终为1:1关系)?