我的HTML代码中的for每个循环都有一个,它将在页面上显示多个按钮。我使用JavaScript,因此只要单击按钮,文本的颜色和背景就应该改变。但是,这似乎仅适用于第一个按钮,而不适用于随后的任何按钮。
HTML:
<input class="big-button" type="button" value="Apply this promotion" id="btn" onclick="status(event)">
JavaScript:
function status() {
if(event.target == document.getElementById("btn")) {
document.getElementById("btn").value = "Copied to clipboard";
document.getElementById("btn").disabled = true;
document.getElementById("btn").style.color = 'white';
document.getElementById("btn").style.background = 'gray';
}
}
我对JavaScript还是很陌生,所以我不确定代码的JavaScript部分是否缺少某些内容,或者是循环导致此功能不起作用。我需要使用循环,因为我还要显示其他需要循环的信息。
答案 0 :(得分:0)
出于安全原因,我希望您在JavaScript中使用addEventListener
。而且您正在迭代按钮,因此您需要使用它,因为id不是id coz id是唯一的,它将在后台返回错误。所以我编辑你的代码。这对我有用。
HTML
<input class="big-button" type="button" value="Apply this promotion" id="btn">
<input class="big-button" type="button" value="Apply this promotion" id="btn">
<input class="big-button" type="button" value="Apply this promotion" id="btn">
<input class="big-button" type="button" value="Apply this promotion" id="btn">
<input class="big-button" type="button" value="Apply this promotion" id="btn">
JavaScript
(function() {
const buttons = document.getElementsByClassName("big-button")
Array.prototype.forEach.call(buttons, function(element) {
element.addEventListener("click", function() {
this.value = "Copied to clipboard"
this.disabled = true
this.style.color = "white"
this.style.background = "gray"
})
})
})()
答案 1 :(得分:0)
您的主要问题似乎是您在多个元素上使用相同的df.to_csv('data.csv', index=False)
。我建议您删除这些id
。
相反,我认为您可以通过使用id
关键字而受益。您可以通过将this
传递到this
事件侦听器的status
函数中来使用:
onclick
现在,传入的变量onclick="status(this)"
引用了您单击的按钮,因此您可以相应地更改其属性。
看看下面的代码片段,以更好地理解:
clickedBtn
function status(clickedBtn) {
clickedBtn.value = "Copied to clipboard";
clickedBtn.disabled = true;
clickedBtn.style.color = 'white';
clickedBtn.style.background = 'gray';
}
答案 2 :(得分:0)
function status() {
event.target.value = "Copied to clipboard";
event.target.disabled = true;
event.target.style.color = 'white';
event.target.style.background = 'gray';
}
<input class="big-button" type="button" value="Apply this promotion" id="btn" onclick="status(event)">
<input class="big-button" type="button" value="Apply this promotion" id="btn" onclick="status(event)">
<input class="big-button" type="button" value="Apply this promotion" id="btn" onclick="status(event)">
<input class="big-button" type="button" value="Apply this promotion" id="btn" onclick="status(event)">
状态功能始终检查相同的按钮ID:“ btn”。因此,它会更改同一按钮元素的样式。将功能修改为以下内容:
function status() {
event.target.value = "Copied to clipboard";
event.target.disabled = true;
event.target.style.color = 'white';
event.target.style.background = 'gray';
}
现在,尝试使用相同的HTML。上面的函数仅更改单击元素的样式。