标签 javascript jquery dom jquery-selectors
考虑以下 HTML。如果我有一个对 元素的 JSON 引用,我如何在这两种情况下获得对外部 元素的引用 <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> 我知道我可以对每个条件进行特殊处理,但我更感兴趣的是“无论你碰巧有多深,爬树直到找到元素 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); } }; 我知道 parent(expr) 方法,但据我所知,它允许您向上过滤父级,并且在找到 expr 之前不要爬树(我希望代码示例能证明我错了) 最佳答案 parents函数做你想做的: $(this).parents("tr:first"); 关于javascript - 是否有 jQuery 选择器/方法来查找特定的父元素 n 级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/699027/ 上一篇:javascript - 在 React Native 中使用 async/await 时出错 下一篇:javascript - 为什么逻辑或不能处理 JavaScript 中的错误抛出? 相关文章: asp.net - 如何获取RadioButtonList的innerText javascript - 从框架的主窗口中的 JS 执行中删除 onbeforeunload Javascript 悬停函数 javascript - Bootstrap 进度条动态元素 - 动态改变宽度 java - 将 DOMSource 转换为 StreamSource 的更简单方法? javascript - 通过 Redux 和 Redux 路由器处理用户身份验证 javascript - Dust.js 逻辑助手的问题 jquery - 将 JSON 对象传输到 MVC 3 中的 View java - 节点列表未填充 javascript - 预加载图像并插入到 DOM 中
<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>
我知道我可以对每个条件进行特殊处理,但我更感兴趣的是“无论你碰巧有多深,爬树直到找到元素 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); } };
我知道 parent(expr) 方法,但据我所知,它允许您向上过滤父级,并且在找到 expr 之前不要爬树(我希望代码示例能证明我错了)
最佳答案
parents函数做你想做的:
$(this).parents("tr:first");
关于javascript - 是否有 jQuery 选择器/方法来查找特定的父元素 n 级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/699027/
相关文章:
asp.net - 如何获取RadioButtonList的innerText
javascript - 从框架的主窗口中的 JS 执行中删除 onbeforeunload
Javascript 悬停函数
javascript - Bootstrap 进度条动态元素 - 动态改变宽度
java - 将 DOMSource 转换为 StreamSource 的更简单方法?
javascript - 通过 Redux 和 Redux 路由器处理用户身份验证
javascript - Dust.js 逻辑助手的问题
jquery - 将 JSON 对象传输到 MVC 3 中的 View
java - 节点列表未填充
javascript - 预加载图像并插入到 DOM 中