javascript获取外部父ID ID [英] javascript obtain outer parent id DIV

查看:71
本文介绍了javascript获取外部父ID ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的结构看起来像下面那个,我正在尝试获取id foo 。如果我们从 onclick冒出 <$ c,那么 DIV 带有ID $ c> func(),这意味着其他 DIVs foo 中包含一个id。但是, foo 中的其他标记可以包含一个id(例如 bye,hello )。

I have a structure that looks like the one below, I'm trying to get the id foo. It is the only DIV with id if we bubble up from the onclick func(), which means that there wont be other DIVs that contain an id inside foo. However, there can be other tags inside foo that contain an id (such as bye, hello).

没有使用任何框架。

<div id="bar"></div>
<div id="foo">
    <p><p>
    <div class="bye">
        <input id="bye" type="text" value="test" />  
        <input id="hello" type="text" value="test" />
        <table>
            <tr><td onclick="func(event)">1</td></tr>
            <tr><td onclick="func(event)">2</td></tr>
        </table>
    </div>
</div>


推荐答案

这应该这样做:

<div id="bar"></div>
<div id="foo">
    <p><p>
    <div class="bye">
        <input id="bye" type="text" value="test" />
        <input id="hello" type="text" value="test" />
        <table>
            <tr><td onclick="func(this)">1</td></tr>
            <tr><td onclick="func(this)">2</td></tr>
        </table>
    </div>
</div>

<script type="text/javascript">
    function func(elt) {
            // Traverse up until root hit or DIV with ID found
        while (elt && (elt.tagName != "DIV" || !elt.id))
            elt = elt.parentNode;
        if (elt) // Check we found a DIV with an ID
            alert(elt.id);
    }
</script>

这篇关于javascript获取外部父ID ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆