javascript, кажется, автоматически отсоединяет слушателей событий от textareas - PullRequest
0 голосов
/ 11 марта 2020

Добрый день, уважаемое сообщество,

Я написал веб-приложение (код ниже), что, если дважды щелкнуть по нему, оно вставит текстовую область в рамку.

Если вы удвоите щелкните текстовую область, она станет зеленой, и, дважды щелкнув ее снова, она станет белой ... (и т. д.)

Проблема заключается в том, что при создании двух или более текстовых областей только самые последние созданный имеет свойство быть переключаемым. Мне кажется, что последние текстовые области как-то теряют свои обработчики событий.

Как мне сделать так, чтобы обработчики событий оставались привязанными к каждой текстовой области?

Спасибо заранее:)

A screenshot of the problem

function randomIntInRange(min, max) { // min and max included
  return Math.floor(Math.random() * (max - min + 1) + min);
}

// Add a double click event listener to the root container
document.getElementById('root_container').addEventListener('dblclick', function(event) {
  var textArea = new TextArea();
  textArea.insertIntoHTML(event.clientX, event.clientY);
});

class TextArea {
  constructor() {
    // Generate a text area id
    this.id = randomIntInRange(1000000000, 9999999999);

    // Create a variable for changing the text area's bg-color in the onDoubleClick(event) method
    this.isToggled = false;
    this.onDoubleClick = this.onDoubleClick.bind(this);
  }

  insertIntoHTML(x, y) {
    // Insert a new text area into the html code
    document.getElementById('root_container').innerHTML += '<textarea id="' + this.id + '"></textarea>';

    // Setting the text area's position
    document.getElementById(this.id).style.position = 'absolute';
    document.getElementById(this.id).style.left = x + 'px';
    document.getElementById(this.id).style.top = y + 'px';

    // Add a double click event listener to the text area
    document.getElementById(this.id).addEventListener('dblclick', this.onDoubleClick);

    // Focus the text area
    document.getElementById(this.id).focus();
  }

  onDoubleClick(event) {
    // Prevent event bubbling
    event.stopPropagation();
    
    /* ******************************************
     *  Toggle the text area's background color
     * ****************************************** */
     
    // If the text area is not yet toggled
    if (!this.isToggled) {
      // Set the background color to green
      document.getElementById(this.id).style.backgroundColor = '#7ce717';
      this.isToggled = !this.isToggled;
    } else {
      // Otherwise to white
      document.getElementById(this.id).style.backgroundColor = '#ffffffff';
      this.isToggled = !this.isToggled;
    }
  }
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#title {
  position: absolute;
  top: -20px;
  left: 200px;
}

#root_container {
  background-color: #797979;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.unselectable {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Set the webpage's title -->
    <title>Web App</title>
    <!-- Include the cascading style sheet -->
    <link rel="stylesheet" type="text/css" href="../css/styles.css">
  </head>
  <body>
    <div id="root_container">
    </div>
    <!-- Include the javascript file -->
    <script src="../javascript/behaviour.js"></script>
  </body>
</html>

1 Ответ

0 голосов
/ 11 марта 2020

В этой строке:

document.getElementById('root_container').innerHTML += '<textarea id="' + this.id + '"></textarea>';

Вы уничтожаете dom и элементы внутри и повторно вводите их. Старые TextAreas удаляются, а события

Вместо innerHTML создайте элемент и добавьте его в свой контейнер с помощью appendChild.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...