Jquery JavaScript单击功能不起作用

时间:2018-03-15 21:40:46

标签: javascript jquery

大家好,我有一个小程序的麻烦,我希望你能帮助我。 问题是当我在div中进行单击时,它假设要添加其他框div中的其他内容,并且它说得很好,但问题是当我试图获取这些div的索引时,它会迭代每次都是div。

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
        <style>
            .contenedora {
                background-color: green;
                width: 300px
            }

            .contenedorb {
                margin-top: 10px;
                background-color: green;
                width: 300px
            }

            .dentro_contenedora {
                background-color: gray;
                height: 40px;
                margin-top: 5px;
            }

            .dentro_contenedorb {
                background-color: gray;
                height: 40px;
                margin-top: 5px;
            }
        </style>
        <script>
            $(function() { // INICIO JQUERY
                /*alert(2)*/
                $('.dentro_contenedora').click(function() {
                    $('.contenedorb').append('<div class="dentro_contenedorb">uno</div>')
                    $('.dentro_contenedorb').click(function() {
                        console.log($(this).index())
                    })
                })
            }) // FIN JQUERY
        </script>
    </head>

    <body>
        <div class="contenedora">
            <div class="dentro_contenedora">uno</div>
            <div class="dentro_contenedora">dos</div>
            <div class="dentro_contenedora">tres</div>
        </div>
        <div class="contenedorb">
        </div>
    </body>

</html>

这是我点击它们时的结果,每次都会迭代

enter image description here

如果我直接在控制台中添加,那就很好。

$('.dentro_contenedorb').click(function(){
    console.log( $(this).index() )
}

0 个答案:

没有答案