我正在尝试创建一个数组来保存元素样式。当用户单击按钮时,应该使阵列中的新元素可见。 这就是我到目前为止所拥有的。该按钮将添加彩色Div。但我正试图用数组扩展它。
下面是我的javascript:
function addObj()
{
var newObj = document.createElement('div');
newObj.style.position = "absolute";
newObj.style.height = "60px";
newObj.style.width = "60px";
newObj.style.top = "60px";
newObj.style.left = "60px";
newObj.style.backgroundColor = "blue";
var docBody = document.getElementsByTagName("body").item(0);
var newElement = document.getElementsByTagName("div").item(0);
var items = new Array();
items[0] = new Array(100,200,'#FF0000');
items[1] = new Array(300,400,'#0FFFCC');
items[2] = new Array(400,500,'#FFFFCC');
items[3] = new Array(600,200,'#3FFFCC');
items[4] = new Array(600,200,'#F3FFCC');
for (var i = 0; i > items.length; i++){
addObj(items[i] [0], items[i] [1]);
// addObjects(items[i] [0], items[i] [1]);
}
docBody.appendChild(newObj);
function newObj(leftPos, topPos, color){
var newObj = addObj(items[i] [0], items[i] [1]);
}
}
这是我的HTML:
<body>
<button onClick="addObj()">
Add Object
</button>
</body>
答案 0 :(得分:0)
点击时添加下一项;
var count = 0;
var items = [
[100, 200, '#FF0000'],
[300, 400, '#0FFFCC'],
[400, 500, '#FFFFCC'],
[600, 200, '#3FFFCC'],
[600, 200, '#F3FFCC']
];
function addObj() {
var target = items[count++];
if (!target)
return;
var newObj = document.createElement('div');
newObj.style.position = "absolute";
newObj.style.height = "60px";
newObj.style.width = "60px";
newObj.style.left = target[0] + "px";
newObj.style.top = target[1] + "px";
newObj.style.backgroundColor = target[2];
document.getElementsByTagName("body").item(0).appendChild(newObj);
}
答案 1 :(得分:0)
I have refactored code little bit, I donnt functionality but its rendering div control with color.
I suggest you to use jquery which will help you to abstract code a lot.
here is the java script code
function addObj()
{
var items = new Array();
items[0] = new Array(100,200,'#FF0000');
items[1] = new Array(100,400,'#0FFFCC');
items[2] = new Array(100,600,'#FFFFCC');
items[3] = new Array(100,800,'#3FFFCC');
items[4] = new Array(100,1000,'#F3FFCC');
for (var i = 0; i < items.length; i++){
newObj(items[i] [0], items[i] [1], items[i] [2]);
}
}
function newObj(leftPos, topPos, color)
{
var docBody = document.getElementById("elements");
var newObj = document.createElement('div');
newObj.style.position = "absolute";
newObj.style.height = "60px";
newObj.style.width = "60px";
newObj.style.top = topPos;
newObj.style.left = leftPos;
newObj.style.backgroundColor = color;
docBody.appendChild(newObj);
}
Here is your HTML code
<body>
<div id="elements">
<button onClick="addObj()">Add Object</button>
</div>
</body>