Javascript - 委托点击事件并检测子元素的位置(与第一个孩子比较)

时间:2014-04-23 10:23:23

标签: javascript

    <div class="parent">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>

当我点击child元素之一时,我找到了使用javascript的合适方式。我发现元素的位置(not coordinate)(例如该元素)是parent元素的第三个子元素。我的提问与Detect child node number

相同

2 个答案:

答案 0 :(得分:0)

<script>
    $(document).ready(function () {        
        $('.child').click(function () {
            alert("Position is" + ($(this).index() + 1))
        });
    });
</script>
 <div class="parent" >
        <div class="child">1</div>
        <div class="child">2</div>
        <div class="child">3</div>
        <div class="child">4</div>
        <div class="child">5</div>
    </div>

答案 1 :(得分:0)

在javascript中你可以使用它支持即低版本

    <script>
    debugger
    window.onload = function () {
        var childs = document.getElementById('parent').childNodes;

        for (var i = 0; i < childs.length; i++) {
            childs[i].onclick = function () {
                debugger
                var pos = indexInParent(this);
                alert(pos+1);
            }
        }
    };
    function indexInParent(node) {
        debugger
        var children = node.parentNode.childNodes;
        var num = 0;
        for (var i = 0; i < children.length; i++) {
            if (children[i] == node) return num;
            if (children[i].nodeType == 1) num++;
        }
        return -1;
    }
</script>
<div class="parent" id="parent">
    <div class="child">
        1</div>
    <div class="child">
        2</div>
    <div class="child">
        3</div>
    <div class="child">
        4</div>
    <div class="child">
        5</div>
</div>