在点击时更改JavaScript中的样式

Changing style in javascript on onclick

本文关键字:JavaScript 样式      更新时间:2023-09-26

我想做几个简单的按钮,每次按下时都会切换颜色。按下按钮还需要将一些唯一的字符串传递给服务器。因此,每次按下按钮时,我都会运行两个功能。我的问题是,当我运行此脚本时,按钮仅在显示警报消息 Msg1 后的时间段内将颜色更改为红色。当我对 Msg2 回答"确定"时,按钮的颜色恢复为绿色。我在这里做错了什么?

<style>
.button { background-color: green; }
.buttonOn { background-color: red; }
</style>
<button id="r1" class="button" onclick="mF1(id)">Relay 1</button>
<script>
function mF1(btn) {
var property = document.getElementById(btn);
alert('Msg1: This is ' + property.className);
if (property.className == 'button')     
    { property.className = 'buttonOn' }
else 
    { property.className = 'button';  }
alert('Msg2: This is ' + property.className);
mF2(btn);            
}
function mF2(id) { window.location.href='?HVAC-' + id; }
</script>

你正在使用 JavaScript 来更改 DOM。

然后,您将location.href设置为新值。

这会导致加载新页面。

新页面没有您对 DOM 所做的修改。


您需要编写代码,以便在页面加载时检查查询字符串并设置适当的类。