【问题标题】:javascript code to change the background color onclicking more buttonsjavascript代码来改变点击更多按钮的背景颜色
【发布时间】:2021-07-25 16:01:36
【问题描述】:

点击按钮时背景颜色应该改变有一个规则,按钮应该由矩阵创建,如下所示。错误是红色是点击任何按钮时唯一的输出

var currColor = 5,
  flag = 1;
var colors = ['red', 'blue', 'green', 'yellow', 'black'];
for (var i = 0; i < 5; i++) {
  document.write('<input type="button" onclick="change()" id="btn" value=' + colors[i] + ' style="background-color:' + colors[i] + ' ;"></input>');
}

function change(i) {
  var colorsName = document.getElementById('btn').value;
  document.body.style.backgroundColor = colorsName;
}

【问题讨论】:

标签: javascript matrix background-color


【解决方案1】:

元素所具有的每个ids 在整个文档中都应该是唯一的。

因此,您应该使用事件的target 而不是使用document.getElementById() 函数:

此外,您不应使用 onclick aatribute 而应使用 HTML 元素的 addEventListener 方法。

那么document.write 不应该被使用。改用 DOM 操作

如果您使用按钮,我建议它是 button 元素而不是 input[type=button]。但这值得商榷。

function change(e){
    var colorsName = e.target.value;
    document.body.style.backgroundColor = colorsName;
}
var currColor = 5, flag = 1;
var colors = ['red', 'blue', 'green', 'yellow', 'black'];
for(var i=0; i<5; i++) {
    var button = document.createElement('button');
    button.type = 'button';
    button.innerText = colors[i];
    button.value = colors[i];
    button.style.backgroundColor = colors[i];
    
    button.addEventListener('click', change)
    document.body.append(button)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2014-10-09
    • 2017-08-02
    • 2014-10-10
    相关资源
    最近更新 更多