3 回答
已采纳
刚毅87
TA贡献345条经验 获得超309个赞
简单写了一段代码, 你参考一下吧
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <style type="text/css"> span{ border: 1px solid black; } </style> </head> <body> <div id="div1">黑色</div> <div id="div2">白色</div> <div id="div3">蓝色</div> <span></span> </body> <script type="text/javascript"> var divs = document.getElementsByTagName('div'); var span = document.querySelector('span'); var arr = ['黑色','白色','蓝色']; for (var i = 0;i < divs.length;i++){ divs[i].index = i; divs[i].onclick = function () { span.innerHTML = arr[this.index] } } </script> </html>
Walk_
TA贡献48条经验 获得超30个赞
<!-- 简单的演示 --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>RunJS</title> </head> <body> <div id="color_button"> <button type="button" value="黑色">黑色</button> <button type="button" value="白色">白色</button> <button type="button" value="蓝色">蓝色</button> </div> <span id="text"></span> <script> var get_button_div=document.getElementById("color_button"); var get_button=document.getElementsByTagName("button"); var get_text=document.getElementById("text"); /* * @element 需要修改值的元素 * @value 需要修改的值 */ function add_value(element,value){ element.innerHTML=value; }; /* * @element_1 需要绑定事件的元素 * @element_2 需要修改值的元素 */ function bingding_event(element_1,element_2){ for(var i=0,j=element_1.length;i<j;i++){ (function(i){ element_1[i].onclick = function(){ add_value(element_2,this.value); } })(i) } }; bingding_event(get_button,get_text); </script> </body> </html>
添加回答
举报
0/150
提交
取消