简体   繁体   English

通过从JavaScript中的函数返回函数来修改div

[英]Modifying div by returning a function from a function in JavaScript

So, my assignment is to pass a div to a function then return a function that will create a new div, assign a class (defined in CSS) and add to the div that was originally passed into the function. 因此,我的任务是将div传递给函数,然后返回一个函数,该函数将创建一个新的div,分配一个类(在CSS中定义),然后添加到最初传递给该函数的div中。

More specifically, the addDivTo() function receives a div id and returns a function. 更具体地说, addDivTo()函数接收一个div id并返回一个函数。 The function being returned receives a class as a parameter, in this function the new div should be created, the class applied and create random location to place in the original div. 返回的函数接收一个类作为参数,在该函数中应创建新的div,应用该类并创建随机位置以放置在原始div中。

It took me some time to wrap my head around this, I think I have the addDivTo() built correctly as I am receiving the function back into the variable, but nothing is happening when trying to pass the class into the return function. 我花了一些时间来解决这个问题,我认为我在将函数接收回变量时正确构建了addDivTo() ,但是尝试将类传递给return函数时没有任何反应。

I apologize, I have a bunch of comments in my code to try and keep straight what I'm attempting to do but I'm obviously not doing something right since nothing is happening! 我很抱歉,我的代码中有很多注释,试图保持我尝试做的事情,但显然我没有做正确的事,因为什么也没发生! If anyone could point me in the right direction or explain what I'm doing wrong I would appreciate it. 如果有人能指出正确的方向或解释我做错了什么,我将不胜感激。

<!doctype html>
<html>
<head>
 <title> Functions: Returning a function from a function </title>
 <meta charset="utf-8">
 <style>
    html, body, div#container {
      width: 100%;
      height: 100%;
      margin: 0px;
      padding: 0px;
    }
    div#container1, div#container2 {
      position: relative;
      height: 300px;
      border: 1px solid black;
    }
    .red {
      position: absolute;
      width: 150px;
      height: 150px;
      background-color: red;
    }
    .blue {
      position: absolute;
      width: 175px;
      height: 175px;
      background-color: lightblue;
    }
    .circle {
      width:100px;
      height:100px;
      border-radius:50px;
      font-size:20px;
      color:#fff;
      line-height:100px;
      text-align:center;
      background:#000
     }
     .squared {
       border: 2x solid black;
     }
 </style>
   <script>
      window.onload = init;
       function init() {    
       //Pass value for div container into addDivTo()
       //addDivTo() will return a function to the variable passed to it
       //when calling function returned from addDivTo pass in name of 
       //class the div should have

      var containerOne = document.getElementById("container1");
      var containerTwo = document.getElementById("container2");
      var colorOne = getComputedStyle(document.body, "red");
      var colorTwo = getComputedStyle(document.body, "blue");
      var shapeSquare = getComputedStyle(document.body, "square");
      var shapeCircle = getComputedStyle(document.body, "circle");

      //call addDivTo() calling containers
     //return function will be contained in the variables

     var newDiv1 = addDivTo(containerOne);   
     var newDiv2 = addDivTo(containerTwo);

     //pass class to function which should return the new div and class 
     //and append to original container passed to addDivTo 

     var addColor = newDiv1(colorOne);
     containerOne.appendChild(addColor);
     var addShape = newDiv1(shapeSquare);
     containerOne.appendChild(addShape);
     var addColor2 = newDiv2(colorTwo);
     containerTwo.appendChild(addColor2);
     var addShape2 = newDiv2(shapeCircle);
     container2.appendChild(addShape2);         
 } 

 function addDivTo (containerIn) {
 //Takes container id and returns a function when called

//Return function takes class, create new div element and add to div 
//passed in the call addDivTo                     
     return function(classToAdd) {
      var divIn = containerIn;   
      var classIn = classToAdd;                  
      var newDiv = document.createElement('div');
      newDiv.id = "funcDiv";
      newDiv.style.left = Math.floor(Math.random() * (newDiv.offsetWidth 
                      = 175)) + "px";
      newDiv.style.right = Math.floor(Math.random() *
                      (newDiv.offsetHeight = 175)) + "px"; 
      newDiv.className = classIn;             
      return newDiv;   
     };

 }  

  </script>
</head>
<body>
  <div id="container1"></div>
  <div id="container2"></div>
</body>
</html>

First off, getComputedStyle doesn't work like that at all. 首先, getComputedStyle根本无法正常工作。 It returns a style object and doesn't take a class for a second argument. 它返回一个样式对象,并且没有第二个参数的类。 Read the docs on MDN. 阅读有关MDN的文档。

Second, there's a p missing for px in your .squared css. 其次, .squared css中的px缺少p

Next, you've got a lot of useless variables that get created only to be passed immediately after, such as divIn and classIn. 接下来,您将创建很多无用的变量,这些变量只能在之后立即传递,例如divIn和classIn。

Finally, ids have to be unique in a document, but your function always creates divs with the same id. 最后,id在文档中必须唯一,但是您的函数始终创建具有相同id的div。

And why do you have to return a function in the first place? 以及为什么必须首先返回一个函数? Couldn't you just make one function called addDivTo(parent, class) which would take care of appending as well as everything else? 您能否仅制作一个称为addDivTo(parent, class)函数addDivTo(parent, class)该函数将负责附加以及其他所有内容?

Start by fixing that and look at the JS console for debug messages. 首先修复该问题,然后查看JS控制台以获取调试消息。

If you use .className property you must only pass the classname. 如果使用.className属性,则必须仅传递类名。 Take a look here: http://www.w3schools.com/jsref/prop_html_classname.asp 在这里看看: http : //www.w3schools.com/jsref/prop_html_classname.asp

You just need to change: 您只需要更改:

var colorOne = getComputedStyle(document.body, "red");
var colorTwo = getComputedStyle(document.body, "blue");

To: 至:

var colorOne = "red";
var colorTwo = "blue";

Here is a working sample: http://codepen.io/anon/pen/KwYYMp 这是一个工作示例: http : //codepen.io/anon/pen/KwYYMp

You're returning a function (that we'll call later) not a new div. 您返回的是一个函数(稍后将调用)而不是新的div。

the addDivTo() function receives a div id and returns a function addDivTo()函数接收一个div ID并返回一个函数

So instead of 所以代替

var newDiv1 = addDivTo(containerOne);

Think of this 想想看

var funcAddToContainerOne = addDivTo(containerOneId);

The function being returned receives a class as a parameter, in this function the new div should be created, the class applied 返回的函数接收一个类作为参数,在该函数中应创建新的div,并应用该类

Now you're on the right track with 现在,您在正确的轨道上

function addDivTo (containerId) {                
    // this is an anonymous function you will assign to a variable
    return function(classToAdd) {
        // 1. create new div
        // 2. add class
        // 3. find containerId
        // 4. append new div to found element
    }
}

And you can call your new anonymous function with the variable you set up earlier: 您可以使用之前设置的变量来调用新的匿名函数:

var funcAddToContainerOne = addDivTo(containerOneId);
funcAddToContainerOne(className);

Now all of your DOM manipulations are removed from the main init() function and embedded in your anonymous function. 现在,您所有的DOM操作都已从主要的init()函数中删除,并嵌入到您的匿名函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM