给div绑定点击事件三个方法

基础代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <style>
        div {
            font-size: 2em;
            width: 250px;
            cursor: pointer /*变成手型*/
        }

        .clickme {
            background-color: #2aabd2;
        }
    </style>
    <script src="//libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<!--代码位置-->
</body>
</html>

方法1-javascript代码绑定

<div class="clickme" id="clickme">事件绑定-点击我</div>
<script>
document.getElementById("clickme").onclick = function () {
    location.href = "http://www.baidu.com/"
};
</script>

方法2-jQuery代码绑定

<div class="clickme" id="clickme">事件绑定-点击我</div>
<script>
$(function () {
    $("#clickme").bind("click", function () {
        location.href = "http://www.baidu.com/"
    });
});
</script>

方法3-addEventListener()代码绑定

<div class="clickme" id="clickme" onclick="eventBindClick(this, 'http://www.baidu.com/');">事件绑定-点击我</div>
<script>
function eventBindClick(obj, href) {
    eventBind(obj, 'click', go(href));
}

function eventBind(obj, eventType, callBack) {
    if (obj.addEventListener) {
        obj.addEventListener(eventType, callBack, false);
    } else if (obj.attachEvent) {
        //window.attachEvent
        obj.attachEvent('on' + eventType, callBack);
    }
}

function go(href) {
   location.href = href;
}
</script>

addEventListener()详细参数说明入口

发表评论