onload函数绑定,byclass数组遍历、this获取整个标签内容
<head> <meta charset="UTF-8"> <title>Title</title> <script> function f() { var ele=document.getElementsByClassName("div1")[0]; console.log(ele.innerHTML); } </script> </head> <body onload="f()"> <div class="div1">hello,jerry</div> </body> </html>
<body> <div class="v1"> <div class="v2">dddd</div> <p id="p1">ppp</p> </div> <script> var ele=document.getElementById("p1"); ele.onclick=function () { alert("asdsa")//其他加引号 //alert(1323)数字不加引号 } var ele1=document.getElementsByClassName("v2");//ele[0].其中可以用数组遍历 for(var i=0;i<ele1.length;i++){ ele1[i].onclick=function () { alert(666) } } </script> </body>
<body> <div class="v1"> <div class="v2">dddd</div> <p id="p1" onclick="func(this)">ppp</p><!--点击p标签-->//this是固定值不可变 </div> <script> function func(hello) { console.log(hello);//可以获取显示整个p标签的所有内容 console.log(hello.previousElementSibling)//找上一个标签 console.log(hello.parentElement) } </script> </body> </html>