简体   繁体   English

如何通过孩子的ID查找父母的ID

[英]How to find a parent's ID through a child's ID

I have a dynamically generated table that will have an ID. 我有一个动态生成的表,它将具有一个ID。 If the table has a radio button, when I click on the radio button I need to get that parent table's ID through javascript. 如果表有一个单选按钮,当我点击单选按钮时,我需要通过javascript获取父表的ID。 How can I do that? 我怎样才能做到这一点?

With jQuery you can use .closest() or .parent() (though parent only looks up 1 level, whereas .closest() goes up until it find something). 使用jQuery,您可以使用.closest().parent() (尽管父级只查找1级,而.closest()会上升直到找到某些内容)。 I've always found .closest() easier and more robust, as it will work if you change the markup (ie you wrap stuff in a <span> or something). 我总是发现.closest()更容易,更健壮,因为如果你改变标记(即你在<span>或其他东西中包装东西)它会起作用。

Anyways, here's the jQuery version: 无论如何,这是jQuery版本:

<input type="radio" onlick="var id = $(this).closest('table').attr('id');" />

If you don't use a library, you can do this with just JavaScript as well. 如果您不使用库,也可以使用JavaScript执行此操作。

The JavaScript: JavaScript:

function findAncestorByTagName(start, tagName) {
    if (tagName.toUpperCase() === start.nodeName.toUpperCase()) {
        return start;
    }
    else if (start === document.body) {
        return false;
    }
    else {
        return findAncestorByTagName(start.parentNode, tagName);
    }
}

The onclick handler you'll have to add: 您必须添加的onclick处理程序:

<input type="radio" onclick="var par = findAncestorByTagName(this, 'div'); if (par && par.id) { /* use par.id */ }" />

With JQuery can get the Parent of an element by element.parent(). 使用JQuery可以通过element.parent()获取元素的Parent。 So when you want the id from the parent you can write element.parent().attr("id); 因此,当你想要父母的id时,你可以写出element.parent()。attr(“id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM