0

单击 tr 内的元素时,我尝试访问 tr。但我不知道元素的确切级别

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

这是我的示例http://jsfiddle.net/mntKr/

<script>
    function getTr (mythis) {
       mythis.parentNode.parentNode.setAttribute('class', 'test');
        // is possible to access tr if i don't know level of a tag
    }

</script>
<div>
    <table>
        <tr>
            <td>
               test
            </td>
            <td>
               <a href="#" onclick="getTr(this);">click me</a>
            </td>
        </tr>
        <tr>
            <td>
                <div>
                   test
                </div>
            </td>
            <td>
                <div>
                   <a href="#" onclick="getTr(this);">click me</a>
                </div>
            </td>
        </tr>
    </table>
</div>

怎么做谢谢!

4

2 回答 2

4

绝对地。继续迭代,mythis.parentNode直到到达 where 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";
}
于 2013-09-06T16:21:44.250 回答
1

jQuery 版本,也支持动态添加tr's.

您可以删除onclickhtml 中的部分。

$(function() {
    $('table').on('click', 'a', function(){
            e.preventDefault(); //so the browser wouldn't navigate elsewhere.
        var tr = $(this).closest('tr');
    });
});
于 2013-09-06T16:24:19.523 回答