0

I'm having trouble figuring out how to pass values from one function to another. I've created a program where I create boxes using values from a form that show up in the webpage. The values I'm talking about are property values of the boxes themselves.

Here is the function where the values are assigned to the boxes:

function addBox(newbox) {  
       for (var i = 0; i < newbox.number; i++) { 
       counter++;
       var id = counter;                          
       var scene = document.getElementById("scene");              
       var div = document.createElement("div"); 
       div.value = id;
       console.log(div.value);                  
       div.className += " " + "box"; 
       div.innerHTML += newbox.name; 
       div.style.backgroundColor = newbox.color; 
       var x = Math.floor(Math.random() * (scene.offsetWidth-101));
       var y = Math.floor(Math.random() * (scene.offsetHeight-101));
       div.style.left = x + "px";
       div.style.top = y + "px"; 
       scene.appendChild(div); 
       div.onclick = display;              
        }                      
      }

Here is the function that I'm having trouble passing the values to. I need to pass them so that I can display them in an alert box when I click on each box:

  function display(e) {
  alert(e.target.toSource());
  }

So far when I click it, I just get an empty pair of brackets in the alert box.

4

1 回答 1

0

我在 JS Fiddle 中试过你的例子:http: //jsfiddle.net/jCC6n/

我看到至少两个问题。

  1. “counter”是未定义的,这会导致代码在第一次尝试递增它时失败。我在函数顶部添加了一个变量声明。
  2. toSource 未定义。我将其替换为“outerHTML”,它适用于 Chrome、IE 和可能的其他浏览器。

通过上述更改,这行得通。

function display(e) {
    alert(e.target.outerHTML);
}

function addBox(newbox) {  
    var counter = 0;
    for (var i = 0; i < newbox.number; i++) { 
        counter++;
        var id = counter;                          
        var scene = document.getElementById("scene");              
        var div = document.createElement("div"); 
        div.value = id;
        div.className += " " + "box"; 
        div.innerHTML += newbox.name; 
        div.style.backgroundColor = newbox.color; 
        var x = Math.floor(Math.random() * (scene.offsetWidth-101));
        var y = Math.floor(Math.random() * (scene.offsetHeight-101));
        //div.style.left = x + "px";
        //div.style.top = y + "px"; 
        scene.appendChild(div); 
        div.onclick = display;              
    }                      
}

addBox({ number: 3, name: "Hello", color: '#C00' });

请注意,使用 onclick 事件处理程序的事件处理因浏览器而异。最好使用了解所有差异并为您提供处理事件的统一方式的 JavaScript 框架。jQuery 可以说是最常用的此类框架。

于 2013-01-18T21:25:39.533 回答