发布时间:2025-12-10 11:20:14 浏览次数:11
以下为onclick的使用技巧,全部经过个人验证,如要转载,请标明出处。
不限于onclick,所有事件都可以这样操作
事件如下:
直接在标签中 οnclick="…",里面写上修改标签属性的语句/输入输出语句
<button onclick="window.alert(window.prompt());this.innerText='9';this.">5</button>开始
按下按钮 5,输入123
显示
5变成9,并且底色改变
如果不行,建议使用Google浏览器
在标签中写 οnclick="函数1();函数2();函数3();"
<button id=d1 onclick="f1();f2();f3()">1</button>太简单,就不演示了
在js种使用 “x.οnclick=函数名;”
<body><button id=d1>1</button></body><script>var b1 = document.getElementById("d1");b1.onclick = f4;function f4() {console.log("第三种方式");//this代表调用该函数的元素对象this.style.backgroundColor = "red";}</script>这是第三种的进阶版,用循环给每个button赋予onclick事件,当点击一个button时,该按钮变红
<body><button id=d1>1</button><button>2</button><button class=c1>3</button><button>4</button><button>5</button><button>6</button></body><script>var s = document.getElementsByTagName("button");function f4() {console.log("第三种方式");this.style.backgroundColor = "red";}//给每个button设置onclick事件for(var i=0;i<s.length;i++){s[i].onclick=f4;}</script>使用 “x.οnclick=function(){…}”,{}之间可以调用函数,也可以直接写js语句。
<body><button id=d1>1</button></body><script>var b1 = document.getElementById("d1");b1.onclick=function(){f4(29,this);console.log("二次输出");}function f4(itemp,ele) {//设置2个形参console.log("第三种方式"+" "+itemp+" "+ele);ele.style.backgroundColor = "red";//this.style.backgroundColor = "red";//this失效}</script>事件监听器例子:
<body><button id=d1>按钮</button><p id=p1></p><script>var x = document.getElementById("d1");//buttonvar x1 = document.getElementById("p1");//p,用来插入语句x1.style.border="1px blue solid";x.addEventListener("mouseover", f1);x.addEventListener("click", f2);x.addEventListener("mouseout", f3);function f1() {x1.innerHTML += "鼠标移入<br>";}function f2() {x1.innerHTML += "鼠标双击<br>";}function f3() {x1.innerHTML += "鼠标移出<br>";}</script></body>经验证:
<script></script>可以写在body的里面,也可以写在外面
还可以写在另一个文档用,<script src="1.js"></script> 链接