Ala*_*orm 51 javascript jquery dom jquery-selectors
请考虑以下HTML.如果我有一个对<button>元素的JSON引用,我怎样才能在两种情况下获得对外部<tr>元素的引用
<table id="my-table">
<tr>
<td>
<button>Foo</button>
</td>
<td>
<div>
<button>Bar</button>
</div>
</td>
</tr>
</table>
<script type="text/js">
$('#table button').click(function(){
//$(this).parent().parent() will work for the first row
//$(this).parent().parent().parent() will work for the second row
//is there a selector or some magic json one liner that will climb
//the DOM tree until it hits a TR, or do I have to code this myself
//each time?
//$(this).????
});
</script>
Run Code Online (Sandbox Code Playgroud)
我知道每种条件我都可以处于特殊情况,但我更感兴趣的是"无论你遇到多么深刻,爬上树直到你找到元素X"的风格解决方案.像这样的东西,但更多jQuery喜欢/更少详细
var climb = function(node, str_rule){
if($(node).is(str_rule)){
return node;
}
else if($(node).is('body')){
return false;
}
else{
return climb(node.parentNode, str_rule);
}
};
Run Code Online (Sandbox Code Playgroud)
我知道父(expr)方法,但从我所看到的是允许你过滤父级一级,而不是爬树直到你找到expr(我喜欢代码示例证明我错了)
Seb*_*Seb 98
在父母的功能你想要做什么:
$(this).parents("tr:first");
Run Code Online (Sandbox Code Playgroud)
ben*_*wey 44
此外,如果您使用的是jQuery 1.3+,则可以使用最接近的方法
$(this).closest("tr");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
57881 次 |
最近记录: |