【问题标题】:Retrieve a childNode of a parent Node with jquery使用 jquery 检索父节点的子节点
【发布时间】:2013-11-26 13:31:03
【问题描述】:

我有一个带有这种形式的 html 表格:

<html>
<table>
    <thead>
        <tr>
            <th idth='keyth'></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class='edit' idtd='keytd'></td>
        </tr>
    </tbody>
</table>
</html>

现在我想在 jquery 中检索离开编辑类的属性“keyth”的内容。 示例:

$(".edit") {

    "th_id": this.parentNode.....childNode.getAttribute("idth"),
    //Here I dont know how to achieve the attribute content

});

感谢您的建议!!!

我终于找到了一个只用 Javascript 的解决方案:

"th_id":this.parentNode.parentNode.parentNode.childNodes[0].childNodes[0].childNodes[0].getAttribute("idth")

【问题讨论】:

  • 看看我的回答。

标签: javascript jquery nodes


【解决方案1】:

这两种方法都有效

Live Demo

$(function() {
  $(".edit").on("click",function() {  
    var $thWithKeyTd = $("th[idth='keyth']");

    var $parentChild = $(this).closest("table").find("th[idth='keyth']");  

  });            
});    

纯 JS

Live Demo

window.onload=function() {
  document.querySelector(".edit").onclick=function() {  
    var thWithKeyTd = document.querySelector("th[idth='keyth']");
    console.log(thWithKeyTd.innerHTML);  
  };            
};    

【讨论】:

  • 不起作用我想我必须做 3 次 parent() 和 3 次 children() 但它不起作用
  • 如何使用 getAttribute?closest().getAttribute('') 实现最接近?
  • getAttribute 不是 jQuery
  • 我想我需要一个只有 Javascript 的解决方案我混合了 Jquery 和 Javascript
  • 在我浪费时间使用 jQuery 之前的有用信息。你可以使用 querySelectorAll 然后
【解决方案2】:

这是一个普通的 JS 风格,它比 jQuery 解决方案更快

    "th_id" : this.offsetParent.querySelector('[keyth]')

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多