gpt4 book ai didi

javascript - js onclick 新创建的元素

转载 作者:行者123 更新时间:2023-11-30 17:07:12 25 4
gpt4 key购买 nike

<分区>

您好,我正在尝试为我的项目创建一个简单的颜色选择器。它应该显示带有彩色 SPANS 的 DIV,每个 span 应该 onclick 调用我的函数 -pickColor()- 及其 onwn 值。

问题是,在单击任何 Span 之后,我的函数只是用数组中的最后一个值而不是对应的值调用。知道如何纠正它吗?

这是我的代码

var colors = [ "303030", "777777", "da0025", "f01800", "ff4300", "fd6c05", "feab07", "ffc91e", "93c900", "54c300", "00ab62", "00c3c4", "009bf0", "006afe", "3f00dd", "9025ff", "ff3ec2", "fe0b6b"];

//颜色选择器变量选择器;

function createPicker(){
//create picker wrapper
picker = document.createElement('div');
picker.id = "colorPicker";
picker.style.display = "none"; // initialy invisible !
picker.style.margin = "0";
picker.style.padding = "0.5em";
picker.style.backgroundColor = "rgb(30,30,30)";
//create picker color options
var newColor;
for (var i = colors.length - 1; i >= 0; i--) {
newColor = document.createElement('span');
newColor.id = colors[i];
//set style for color option
newColor.style.display = "inline-block";
newColor.style.width = "50px";
newColor.style.height = "50px";
newColor.style.margin = "0";
newColor.style.padding = "0";
newColor.style.backgroundColor = "#"+colors[i];
//add onclick function

newColor.addEventListener("click", function f(){pickColor( colors[i] )}, true);

//append option
picker.appendChild(newColor);
};
//append colorPicker to file
document.getElementById('here').appendChild(picker); // value must be set to the parent elements id !
}

function displayPicker(){
picker.style.display = "inline-block";
}

function pickColor(id){
//set value
console.log(id);
var input = document.getElementById('color'); // must be the 'input' elements id that we want to set !
//console.log(input);
input.value = id;
// hide picker
picker.style.display = "none";
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com