【问题标题】:Why doesn't this button change text whenever it's clicked, it changes only the first time为什么这个按钮在点击时不改变文本,它只在第一次改变
【发布时间】:2020-08-04 14:53:43
【问题描述】:

我有一个问题,我正在创建一个函数来更改对象数组中书籍的阅读状态。它应该像这样工作,每当我按下按钮并且其文本内容为“已读”时,它应更改为“未读”。如果我再次按下同一个按钮,它应该会返回“读取”,但问题是,它没有,它只有在我第一次单击按钮时才有效。

document.querySelector(".main").addEventListener('click', function(e) {
  if (e.target.classList.contains("book_status")) {
    let bookCard = e.target.parentElement.parentElement;
    // console.log(e.target.textContent)
    if (e.target.textContent = 'Not read') {
      e.target.textContent = 'Read';
    } else if (e.target.textContent = 'Read') {
      e.target.textContent = 'Not read';
    }
  }});

【问题讨论】:

  • = 应该是 === 或 ==。 = 用于分配。 === 和 == 用于比较。

标签: javascript button addeventlistener


【解决方案1】:

你正在测试你没有设置的东西。试试这个来调试:

document.querySelector(".main").addEventListener('click', function(e) {
  if (e.target.classList.contains("book_status")) {
    let bookCard = e.target.parentElement.parentElement;
    // console.log(e.target.textContent)
    if (e.target.textContent = 'Not read') {
      e.target.textContent = 'Read';
    } else if (e.target.textContent = 'Read') {
      e.target.textContent = 'Not read';
    } else {
      console.log('Unknown textContent. e.target.textContent = ' + e.target.textContent);
    }
  } else {
    console.log('e.target.classList DOES NOT include book_status');
  }
});

【讨论】:

    【解决方案2】:

    = 是赋值运算符,== 用于评估

    document.querySelector(".main").addEventListener('click', function(e) {
      if (e.target.classList.contains("book_status")) {
        let bookCard = e.target.parentElement.parentElement;
        // console.log(e.target.textContent)
        if (e.target.textContent == 'Not read') {
          e.target.textContent = 'Read';
        } else if (e.target.textContent == 'Read') {
          e.target.textContent = 'Not read';
        }
      }});
    

    【讨论】:

      【解决方案3】:

      如果没有 HTML,就很难准确地说出哪里会出错。但是一个错字立即引起了我的注意:

      if (e.target.textContent = 'Not read') 
      

      和

      } else if (e.target.textContent = 'Read') {
      

      应该有一个== 而不是= ...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-23
        • 1970-01-01
        • 2021-04-14
        • 2022-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-03
        相关资源
        最近更新 更多