JS中添加事件
方法一
body
<div onclick="a()"></div>
<div class="test"></div>
JS
写法一
function a(){
console.log(111);
i()
}
function i(){
var testJS = document.getElementsByClassName("test")[0]
console.log(testJS);
testJS.addEventListener("click", function () {
console.log("111");
})
}
写法二
function a(){
console.log(111);
i()
}
function i(){
var testJS = document.getElementsByClassName("test")[0]
console.log(testJS);
testJS.addEventListener("click", test, true)
}
fucntion test(){ console.log("111"); }
实现效果
点击蓝色部分,给红色部分添加点击事件。蓝色部分的点击事件打印数字“111”,红色部分打印字符串“111”。
以上遇到需要动态添加的情况上面就不行了
方法二(用setAttribute给元素加属性onclick)
body
<div onclick="a()"></div>
<div class="test"></div>
JS
function i(){
var testJS = document.getElementsByClassName("test")[0]
testJS.setAttribute("onclick", "test()");
}
function test() {
console.log("111");
}
解除绑定事件可以用removeEventListener()
实现效果
点击蓝色部分,给红色部分添加点击事件。蓝色部分的点击事件打印数字“111”,红色部分打印字符串“111”。
方法三(onclick,可以在vue中使用)
body
<div onclick="a()"></div>
<div class="test"></div>
js
function i(){
var testJS = document.getElementsByClassName("test")[0]
testJS.onclick = function () {
test();
};
}
function test() {
console.log("111")
}
解除绑定
document.getElementById("id").onclick=null;
实现效果
点击蓝色部分,给红色部分添加点击事件。蓝色部分的点击事件打印数字“111”,红色部分打印字符串“111”。
JQ中添加事件
这个没有具体测试,是在资料中摘录的一些
方法一
$(selector).click(function)
方法二
$(selector).on(event,childSelector,data,function)
// event _ 需要添加的js事件
//childSelector _ 只能添加到指定的子元素上的事件处理程序
//data _ 调用函数时需要传递的参数
// function _ js函数发生时触发的事件
方法三
//在id为div_link的元素中动态追加a
$(selector).html('<a id="div_link">链接点击</a>');