1

Имеется textarea#text и отдельно стоящий div. При вводе текста (oninput) формируется ajax-запрос, который выводит в div (ранее совершенно пустой) строки до 600 штук (p.matches), в которых встречаются символы из textarea. Мне нужно при двойном клике на любой из p.matches вывести в консоль его innerHTML. Не могу связать два фрагмента кода в один...

Первый:

window.onload = function(){

    var text = document.querySelector('#text');
    var old_classifieds = document.querySelector('#old_classifieds');

    text.oninput = function(){
        var find = 'find=' + text.value;

        var xhr3 = new XMLHttpRequest();
        xhr3.open('POST', 'findPhone.php');
        xhr3.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr3.send(find);

        xhr3.onreadystatechange = function(){
            if(xhr3.readyState == 4 && xhr3.status == 200){
                old_classifieds.innerHTML = xhr3.response;
            }       
            else{
                old_classifieds.innerHTML = 'Ошибка!';
            }
        }
    }

}

Второй:

var matches = document.querySelectorAll('p.matches');
matches.forEach(function(item){
    item.ondblclick = function(){
        console.log(item.innerHTML);
    }
})

Думаю, дело в том, что при загрузке страницы p.matches еще не существуют и формируются php-обработчиком. Но когда они есть и в консоль ввести код номер 2, то все начинает работать.

1 ответ 1

1

Вариант 1:

...
if(xhr3.readyState == 4 && xhr3.status == 200){
  old_classifieds.innerHTML = xhr3.response;

  var matches = document.querySelectorAll('p.matches');
  matches.forEach(function(item){
    item.ondblclick = function(){
      console.log(item.innerHTML);
    }
  });
}       
...

Вариант 2:

var old_classifieds = document.querySelector('#old_classifieds');

old_classifieds.addEventListener("dblclick", function(e) {
  if (e.target.tagName == "P" && e.target.classList.contains("matches")) {
    console.log(e.target.innerHTML);
  }
});
<div id="old_classifieds">
  <p class="matches">The walrus and the carpenter</p>
  <p class="matches">Walked for a mile or so...</p>
</div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.