簡體   English   中英

Javascript-如何通過單擊tr中的元素(動態級別)來訪問tr

[英]Javascript - How to access tr by click a element (dynamic level) inside tr

單擊tr中的元素時,我嘗試訪問tr。 但是我不知道元素的確切水平

如果我不知道元素級別,可以訪問tr嗎? (我想使用JavaScript Basic)

這是我的示例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>

怎么做,謝謝!

絕對。 繼續迭代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');
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM