js、jQuery的事件绑定bind、on
1 //js原生设置自定义属性 2 document.getElementById('a1').setAttribute('data-num', 'abcd'); 3 4 //js原生添加点击事件 并输出当前对象的自定义属性data-num值 5 document.getElementById('a1').onclick = function () { alert( this.getAttribute('data-num'))}; 6 7 //选取class名为aa1的a标签,得到一个数组,遍历数组添加点击事件 8 var arr= document.getElementsByClassName('aa1'); 9 for (var i = 0; i < arr.length; i++) { 10 arr[i].onclick = function () { alert(this.getAttribute('data-num')) }; 11 } 12 13 //原生添加的点击事件不覆盖,会追加一个点击事件 14 document.getElementById('a1').addEventListener('click', function () {alert(123) }); 15 $('#a1').click(function () {alert('jQuery绑定click输出') }); //不能用于动态 16 $('#a1').bind('click', function () {alert('jquery输出bind') }); 17 $('#a1').on('click', function () { alert('jquer绑定on')})
bind、on绑定可以在动态添加元素后依然生效。