抄大神的代码练手,为什么没有反应呢?

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>Title</title>
<style>
    *{
        margin:0;
        padding:0;
    }
    #outer{
        width:500px;
        margin:50px auto;
        text-align:center;
    }
    #inner{
        width:100px;
        height:100px;
        background:black;
        margin:20px auto;
    }
    p{
        width:100px;
        height:50px;
        background:red;
    }
</style>
<script src="changeStyle.js"></script>

</head>
<body>
<div id="outer">

<input type="button" value="变宽">
<input type="button" value="变高">
<input type="button" value="变色">
<input type="button" value="隐藏">
<input type="button" value="重置">
<div id="inner"></div>

</div>

<p width="300px"></p>
<script>

var op=document.getElementsByTagName("p")[0];
op.style.border="2px solid yellow";
op.style.cssText="";

</script>
</body>
</html>

window.onload=function() {

var abtn = document.getElementsByTagName("input");
var odiv = document.getElementById("inner");
var astyle = ["width", "height", "backgroundColor", "display", "display"];
var avalue = ["200px", "200px", "red", "none", "block"]
function changeStyle(obj, attr, value) {
    obj.style[attr] = value;
};
/* for (var i = 0; i < abtn.length; i++) {
    abtn[i].onclick = (function (i) {
             console.log(i);//检查了下i的值都能依次取到。
            i== abtn.length - 1 && (odiv.style.cssText = "");
            changeStyle(odiv, astyle[i], avalue[i]);
    })(i)
}*/
}

模仿大神(http://fgm.cc/learn/lesson1/01.html)的代码做练习,结果我抄都没抄成功,请问是什么原因呢?
阅读 1.8k
2 个回答

因为你给btn赋的事件处理函数是函数的返回值,而你的返回值是空值,也就是说事件处理函数都是空的,自然就没有效果。

 abtn[i].onclick = (function (i) {
                    console.log(i);//检查了下i的值都能依次取到。
                    return function() {
                        i == abtn.length - 1 && (odiv.style.cssText = "");
                        changeStyle(odiv, astyle[i], avalue[i]);
                    }
                    
            })(i)
  /* for (var i = 0; i < abtn.length; i++) {
        (function(i){
            abtn[i].onclick = function (i) {
                 console.log(i);//检查了下i的值都能依次取到。
                i== abtn.length - 1 && (odiv.style.cssText = "");
                changeStyle(odiv, astyle[i], avalue[i]);
            }
        })(i)
    }*/
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题