这种情况怎么样才获取到按钮?

我想获取到动态创建出来的按钮 但是现在的需求是获取按钮的代码不能写到oBtn1.onclick里面 这种情况应怎么办呢?用原生JS有什么办法吗?

下面这样写在外面获取不到

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload=function(){
            var oBtn1=document.getElementById('btn1');
            var oBtn2=document.getElementById('btn2');
            oBtn1.onclick=function(){
                oInput=document.createElement('input');
                oInput.type='button';
                oInput.value='bbb';
                oInput.name='bbb';
                document.body.appendChild(oInput);
            }
            var oBtn2=document.getElementsByName('bbb');
            for(i=0;i<oBtn2.length;i++){
                oBtn2[i].onclick=function(){
                    alert(oBtn2.length);
                }
            }
        }
    </script>
</head>
<body>
<button id="btn1">aaa</button>
</body>
</html>
阅读 2.5k
4 个回答

你的var oBtn2=document.getElementsByName('bbb');在页面加载完成就执行了,此时还没有任何的新创建的bbb

window.onload = function () {
    var oBtn1 = document.getElementById('btn1');
    oBtn1.onclick = function () {
        oInput = document.createElement('input');
        oInput.type = 'button';
        oInput.value = 'bbb';
        oInput.name = 'bbb';
        oInput.onclick = funcOnBtn2;
        document.body.appendChild(oInput);
    }
    function funcOnBtn2(){
        var oBtn2 = document.getElementsByName('bbb');
        alert(oBtn2.length);
    }
}

window.onload只在页面初始化的时候运行一次,你写在外面当然拿不到,当时还没有name是bbb的元素。
可你不点id是btn1的元素就不会动态去追加,所以你的需求是什么?

你的oBtn2[i].onclick必须写在创建后面,调用也行,不然拿什么点击

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload=function(){
            var oBtn2;
            var oBtn1=document.getElementById('btn1');
            oBtn1.onclick=function(){
                var oInput=document.createElement('input');
                 oInput.type='button';
                 oInput.value='bbb';
                 oInput.name='bbb';
                document.body.appendChild(oInput);
                oBtn2=document.getElementsByName('bbb');
                aaa();
            }
            function aaa(){
                for(var i=0;i<oBtn2.length;i++){
                    oBtn2[i].onclick=function(){
                        alert(oBtn2.length);
                    }
                }  
            }
        }
    </script>
</head>
<body>
<button id="btn1">aaa</button>
</body>
</html>

楼上说的都对 你的DOM节点是你的按钮点击生成的 就算是获取也在你的点击事件这边入手,毕竟那是生他的地方。
就像这样
`btn.onclick = function(){

var div = document.createElement('div');
div.innerHTML = "123";
document.body.appendChild(div);
 console.log(document.querySelectorAll("div").length)

}
`
不然的话 你没准想让你的创建的节点做点什么样的 骚操作 类似与这样:
`document.onclick = function(e){

            if(e.target.nodeName.toLowerCase() == 'div'){
                console.log(1)
            }
        }`
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题