我想将CSS设计放在我的代码中,并在父按钮上显示绿色,在子按钮上显示为黄色
function myFunction(btn) {
var counter = parseInt(btn.getAttribute('data-counter'));
var button = document.createElement('button');
button.innerHTML = btn.id + '_' + counter;
button.id = btn.id + '_' + counter;
button.setAttribute('data-counter', '1');
button.setAttribute('onclick', 'myFunction(this)');
document.body.appendChild(button);
btn.setAttribute('data-counter', ++counter);
}
<button id="btn_rv" onclick="myFunction(this)" data-counter="1">Main Button</button>
答案 0 :(得分:1)
此代码执行以下操作:
根据您的要求修改代码。
function myFunction(btn) {
var x = document.getElementsByTagName("button");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "";
}
btn.style.background='green';
var counter = parseInt(btn.getAttribute('data-counter'));
var button = document.createElement('button');
button.innerHTML = btn.id + '_' + counter;
button.id = btn.id + '_' + counter;
button.setAttribute('data-counter', '1');
button.setAttribute('onclick','myFunction(this)');
document.body.appendChild(button);
btn.setAttribute('data-counter', ++counter);
button.style.background='yellow';
}
<button id="btn_rv" onclick="myFunction(this)" data-counter="1">Main Button</button>
答案 1 :(得分:0)
您应该为任何元素样式使用类。内联样式可能会使代码重复且难以维护。
function myFunction(btn) {
var counter = parseInt(btn.getAttribute('data-counter'));
var button = document.createElement('button');
button.innerHTML = btn.id + '_' + counter;
button.id = btn.id + '_' + counter;
button.setAttribute('data-counter', '1');
button.setAttribute('onclick', 'myFunction(this)');
button.className = "child";
document.body.appendChild(button);
btn.setAttribute('data-counter', ++counter);
btn.className = "parent"
}
&#13;
.parent{
background:green;
}
.child{
background:yellow;
}
&#13;
<button id="btn_rv" onclick="myFunction(this)" data-counter="1">Main Button</button>
&#13;