js 增加鼠标点击监听事件,为什么点击了无效也不报错?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #cs2{
            height: 800px;
            width: 500px;
            background-image: url("./psd001.png");
            text-align: center;
            display: none;
        }

        #cs1{
            height: 350px;
            width: 200px;
        }
    </style>
</head>
<body>

<div id='cs1'>
    <img src="vv.png">
</div>


<div id='cs2'>
    123
</div>


<script>
    /*
    function show()
    {
        console.log('鼠标点解了')
    }
    */


    function show(n)
    {
        console.log('鼠标经过了')
        document.getElementById(n).style.display="block";
    }


    function hide(n)
    {
        document.getElementById(n).style.display="none";
    }

    //document.getElementById('cs1').onmouseover = show('cs2');

    //document.getElementById('cs1').onmouseout=hide('cs2');

    var cs1 = document.getElementById('cs1');
    if(cs1.attachEvent){
        cs1.attachEvent('onclick',function () {//添加一个单击事件(单击时触发function函数)
            show('cs2')
        });
    }else if(cs1.addEventListener) {
        cs1.addEventListener('onclick',function () {//添加一个单击事件(单击时触发function函数)
            show('cs2')
        });
    }




</script>



</body>
</html>
阅读 5.2k
3 个回答
cs1.attachEvent('onclick',function(){});
//是 click 不是 onclick
cs1.addEventListener('click',function(){});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #cs2{
            height: 800px;
            width: 500px;
            background-image: url("./psd001.png");
            text-align: center;
            display: none;
        }

        #cs1{
            height: 350px;
            width: 200px;
        }
    </style>
</head>
<body>

<div id='cs1'>
    <img src="vv.png">
</div>


<div id='cs2'>
    123
</div>


<script>
    /*
    function show()
    {
        console.log('鼠标点解了')
    }
    */


    function show(n)
    {
        console.log('鼠标经过了')
        document.getElementById(n).style.display="block";
    }


    function hide(n)
    {
        document.getElementById(n).style.display="none";
    }

    //document.getElementById('cs1').onmouseover = show('cs2');

    //document.getElementById('cs1').onmouseout=hide('cs2');

    var cs1 = document.getElementById('cs1');
    if(cs1.attachEvent){
        cs1.attachEvent('onclick',function () {//添加一个单击事件(单击时触发function函数)
            show('cs2')
        });
    }else if(cs1.addEventListener) {
        cs1.addEventListener('click',function () {//添加一个单击事件(单击时触发function函数)
            show('cs2')
        });
    }




</script>



</body>
</html>

click和onclick是两种用法,onclick是在html代码中声明对此html代码绑定一个点击事件,但是在js里面是需要使用click来声明点击事件

例如
html: <input type='test' onclick="function();">
js: cs1.attachEvent('onclick',function());

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题