一、js获取元素对象方法
1、根据ID属性获取元素
<div id="result"></div>
<script>
const result = document.getElementById('result');
<script>
2、根据name属性获取元素
<button name="btn">点击按钮</button>
<script>
const btn = document.getElementsByName('btn');
</script>
3、通过classname获取元素
<button class="btn">点击按钮</button>
<script>
const btn = document.getElementsByClassName("btn");
</script>
4、通过标签名获取元素
<button id="btn">点击按钮</button>
<script>
const btn = document.getElementsByTagName("button")[0];
</script>
5、 根据选择器获取元素
只返回元素中的第一个
<button class="btn">点击按钮</button>
<script>
const btn = document.querySelector("button");
</script>
二、常见事件绑定
鼠标点击事件
1、DOM事件中绑定 onclick事件
<button id="btn" onclick="f1()">点击按钮</button>
<script>
function f1() {
console.log("hello btn");
}
</script>
2、js代码中绑定 onclick事件
<button id="btn">点击按钮</button>
<script>
// 获取元素对象
document.getElementById('btn').onclick = function(){
console.log("hello btn");
}
</script>
3、AJCAX绑定事件监听函数addEventListener()
<button id="btn">点击按钮</button>
<script>
const btn = document.getElementById('btn');
btn.addEventListener('click',function(){
console.log("hello btn");
})
</script>
键盘按下事件
<script>
window.onkeydown = function (){
console.log("hello keyboard");
}
</script>
鼠标移入事件
<script>
const btn = document.getElementById('btn');
btn.addEventListener('mouseover',function(){
console.log("hello btn");
})
</script>