我正在使用Chrome扩展程序。我正在尝试实现一个按钮,但根本无法正常工作。
我确保脚本位于正文的末尾(在DOM之后),所有拼写均正确无误,等等。它甚至可以复制/粘贴到W3Schools TryIt编辑器中(我也咨询过)。 / p>
<button type="button" id="trackToggleButton" onclick="trackToggle()">T</button>
<!-- other stuff -->
<script>
var trackingEnabled = true;
function trackToggle() {
if (true) {
document.getElementById("trackToggleButton").innerHTML = "Tracking currently enabled. Click to disable.";
trackingEnabled = false;
} else {
document.getElementById("trackToggleButton").innerHTML = "Tracking currently disabled. Click to disable.";
trackingEnabled = true;
}
</script>
无论我做什么,它都会完全忽略脚本,并且不会更改初始值。同样,它甚至可以在W3Schools TryIt编辑器中完美运行。
编辑:它可以正常工作。我从按钮标记中删除了onclick,并将其放在单独的.js文件中:
function trackToggle() {
if (trackingEnabled) {
document.getElementById("trackToggleButton").innerHTML = "Tracking currently disabled. Click to enable.";
trackingEnabled = false;
} else {
document.getElementById("trackToggleButton").innerHTML = "Tracking currently enabled. Click to disable.";
trackingEnabled = true;
}
}
document.getElementById("trackToggleButton").addEventListener('click', trackToggle);