我的 HTML 按钮代码有问题吗?

Is there something wrong with my HTML code for a button?

我有一个按钮,它应该在单击时打开一些文本,并在再次单击时关闭文本。这是它的代码:

<button id = "hello" type="button" onclick="document.getElementById('demo').innerHTML = buttonScript">
    wow look a button
</button>
<p id = "demo">

</p>
</body>
<script>
    var buttonScript;
    if (document.getElementById('demo').innerHTML === "Hello there! Click the button again to close it."){
        buttonScript = " ";
    }
    else {
        buttonScript = "Hello there! Click the button again to close it.";
    }
</script>

点击一次有效,再次点击文字不会消失。我不确定为什么会这样,有人可以告诉我我的菜鸟错误在哪里吗?

问题是每次您的按钮被点击时,它都需要进行评估。您只在页面加载时进行一次评估。您的点击事件没有任何逻辑,它只是一个语句 - <p> 设置为具有当前的 buttonScript - 但 buttonScript 永远不会改变。

在这种情况下使用函数要容易得多。在这个函数中,我们有一行:el.innerHTML = el.innerHTML.trim() === buttonScript ? "" : buttonScript 表示 IF 元素的 innerHTML(在删除任何额外的空格之后)== buttonScript 然后将其设置为空,否则将其设置为 buttonScript

window.onload = function() {
  document.getElementById('hello').addEventListener('click', doTheThing);
  }

  function doTheThing(e) {
    var buttonScript = "Hello there! Click the button again to close it."
    let el = document.getElementById('demo');
    el.innerHTML = el.innerHTML.trim() === buttonScript ? "" : buttonScript
  }
button {
  margin: 0 auto;
  display: block;
}
<button id="hello" type="button">
    wow look a button
</button>
<p id="demo"></p>

现代 JS 提供了许多工作工具,所以我将解释其中的一些。

  1. 在函数外缓存你的元素。我喜欢 querySelector or querySelectorAll,因为这些方法允许我们使用 CSS 其他节点列表实际上不可用的属性。

  2. 现代 JS 不再真正使用内联 JS。我们拾取元素并向它们添加 addEventListener

  3. 元素有一个 classList 方法,允许我们在一个 class 状态和另一个状态之间切换,只要您在 CSS 中设置了那个。

// Cache the elements
const button = document.querySelector('button');
const div = document.querySelector('#demo');

const buttonScript = 'Hello there! Click the button again to close it.'

// Add the text to your div
div.textContent = buttonScript;

// Add the click listener to the button
button.addEventListener('click', handleClick, false);

function handleClick() {

  // Toggle the hidden class on and off
  // when you click the button
  div.classList.toggle('hidden');
}
button { margin: 0 auto; display: block; }
.hidden { visibility: hidden; }
<button>wow look a button</button>
<p class="hidden" id="demo"></p>