JS 给HTML绑定事件注意

有三种添加方式:

1. 绑定事件
    <div id='i1' onkeydown='func(this,event,123);'> 点我 </div>
    function func(a,b,c){
        // a -> 当前被点击的标签对象  document.getElementById('i1')
        // b -> 当前事件相关的信息
        // c = 123
    }
           
2. 绑定事件 ***************(推荐第二种) 注意绑定的函数不能加括号,否则会自动调用
    <div id='i1'> 点我 </div>
    <script>
        document.getElementById('i1).onclick = function(event){
            // event -> 当前事件相关的信息
            // this  -> 当前被点击的标签对象
        }
    </script>
    
3. 绑定事件
    document.getElementById('i1').addEventListener('click',function(){
        console.log(111);
    },true)
    document.getElementById('i1').addEventListener('click',function(){
        console.log(222);
    },true)
    
   PS: addEventListener第三个参数
       默认:
            事件冒泡
            捕获式

 

示例1(无参数的传递):

<form id="search" action="https://www.sogou.com/web" method="post">
                <input id="searchKey" type="text" name="query" value="请输入关键字">
                <a id="searchSubmit"><i style="cursor: pointer;" class="fa fa-search fa-2x" aria-hidden="true">&nbsp;</i></a>
            </form>
function searchClick() {
    document.getElementById("search").submit();
}
document.getElementById("searchSubmit").onclick = searchClick;

 

示例2(有参数的传递):

<div class="body-menu">
            <div class="item">
                <div class="title">
                    菜单001
                </div>
                <div class="subtitle">
                    <a href="#">子菜单01</a>
                    <a href="#">子菜单02</a>
                    <a href="#">子菜单03</a>
                </div>
            </div>
            <div class="item">
                <div class="title">
                    菜单002
                </div>
                <div class="subtitle hide">
                    <a href="#">子菜单01</a>
                    <a href="#">子菜单02</a>
                    <a href="#">子菜单03</a>
                </div>
            </div>
            <div class="item">
                <div class="title">
                    菜单003
                </div>
                <div class="subtitle hide">
                    <a href="#">子菜单01</a>
                    <a href="#">子菜单02</a>
                    <a href="#">子菜单03</a>
                </div>
            </div>

        </div>

js代码,给多个DOM元素绑定onclick ,并且传递 this参数

function changeMenu(currentTag) {
    alert(currentTag.innerText);
    var contentTag = currentTag.nextElementSibling;
    contentTag.classList.remove("hide");
    var itemList = contentTag.parentElement.parentElement.children;
    for(var i=0; i<itemList.length; i++){
        var loopItem = itemList[i];
        if(loopItem != contentTag.parentElement){
            loopItem.lastElementChild.classList.add("hide")
        }
    }
}

var menus = document.getElementsByClassName("title");
for(var i=0; i<menus.length ;i++){
    menus[i].onclick = function(){
        changeMenu(this);
    }
}

 

posted @ 2017-04-17 17:09  Vincen_shen  阅读(259)  评论(0)    收藏  举报