Javascript-如何通过单击tr中的元素(动态级别)来访问tr

Javascript-如何通过单击tr中的元素(动态级别)来访问tr,javascript,Javascript,我试图在单击tr中的某个元素时访问tr,但我不知道该元素的确切级别 如果我不知道元素的级别,是否可以访问tr?(我想使用javascript basic) 这是我的例子 函数getter(mythis){ mythis.parentNode.parentNode.setAttribute('class','test'); //如果我不知道标签的级别,是否可以访问tr } 测试 测试 怎么做谢谢 当然。继续向上迭代mythis.parentNode,直到到达mythis.nodeName==“

我试图在单击tr中的某个元素时访问tr,但我不知道该元素的确切级别

如果我不知道元素的级别,是否可以访问tr?(我想使用javascript basic)

这是我的例子


函数getter(mythis){
mythis.parentNode.parentNode.setAttribute('class','test');
//如果我不知道标签的级别,是否可以访问tr
}
测试
测试

怎么做谢谢

当然。继续向上迭代mythis.parentNode,直到到达mythis.nodeName==“TR”,如下所示:

function getTr(mythis) {
    while(mythis.nodeName != "TR") mythis = mythis.parentNode;
    // may want to add some additional error checking, just in case this function
    // gets called by something that's not in a TR
    mythis.className = "test";
}

当然。继续向上迭代mythis.parentNode,直到到达mythis.nodeName==“TR”,如下所示:

function getTr(mythis) {
    while(mythis.nodeName != "TR") mythis = mythis.parentNode;
    // may want to add some additional error checking, just in case this function
    // gets called by something that's not in a TR
    mythis.className = "test";
}

jQuery版本还支持动态添加的
tr

您可以删除html中的
onclick
部分

$(function() {
    $('table').on('click', 'a', function(){
            e.preventDefault(); //so the browser wouldn't navigate elsewhere.
        var tr = $(this).closest('tr');
    });
});

jQuery版本还支持动态添加的
tr

您可以删除html中的
onclick
部分

$(function() {
    $('table').on('click', 'a', function(){
            e.preventDefault(); //so the browser wouldn't navigate elsewhere.
        var tr = $(this).closest('tr');
    });
});
不错的解决方案(+1)!为了完整起见:大多数库都有自己的
up
函数(与上述功能完全相同),以防您使用类似Prototype的东西。很好的解决方案(+1)!只是为了完整性:大多数库都有自己的
up
函数(与上述功能完全相同),以防您使用类似于Prototype的东西。