AJAX—addEventListener()方法
- addEventListener()方法用于向指定元素添加事件句柄;
- 可用removeEventListener()方法移除事件的句柄
语法:
result.addEventListener(event,function,userCapture);
click鼠标点击事件
<body>
<div id="result"></div>
<script>
//获取元素对象
const result = document.getElementById('result');
//绑定事件 mouseover 鼠标移入
result.addEventListener("click", function() {
result.innerHTML = "你好";
})
</script>
</body>
鼠标移入(mouseover)/移出(mouseout)事件
<body>
<div id="result"></div>
<script>
//获取元素对象
const result = document.getElementById('result');
//绑定事件 mouseover 鼠标移入
result.addEventListener("mouseover",OverFunction);
//绑定事件 mouseout 鼠标移出
result.addEventListener("mouseout",OutFunction);
function OverFunction() {
result.innerHTML = "你好";
}
function OutFunction() {
result.innerHTML = " ";
}
</script>
</body>
传递参数
<body>
<h1>加法计算器</h1>
<input type="text" id="txt1" value=""> <br/>
<input type="text" id="txt2" value=""> <br/>
<button>确定</button>
<div id="result" style="width:200px; height:100px; border: solid 1px blue;"></div>
<script>
//获取元素
//getElementsByTagName 获取多个 是数组 需要遍历一下 里面只有一个时需要加下标 [0]
var btn = document.getElementsByTagName("button")[0];
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
var result = document.getElementById("result");
//绑定事件
btn.addEventListener("click", function() {
console.log(txt1.value);
console.log(txt2.value);
var open1 = parseInt(txt1.value);
var open2 = parseInt(txt2.value);
Function(open1, open2);
})
function Function(a, b) {
var s = a + b;
result.innerHTML = s;
}
</script>
</body>