0

Я искал это решение везде, но не смог найти ответ, который мог бы мне помочь. Мои теги отображаются с помощью ajax из базы данных таким образом, Код:

function all() {
    // Ajax config
    $.ajax({
        type: "GET", //we are using GET method to get all record from the server
        url: 'all.php', // get the route value
        success: function (response) {//once the request successfully process to the server side it will return result here
            
            // Parse the json result
            response = JSON.parse(response);

            var html = "";
            // Check if there is available records
            if(response.length) {
                html += '<div class="list-group">';
                // Loop the parsed JSON
                $.each(response, function(key,value) {
                    // Our employee list template
                    html += '<a href="#" class="list-group-item list-group-item-action">'; 
                    html += "<p class='m-0'>" + value.let_txt_3 + "</p>";
                    html += "<p class='m-0'>" + value.let_txt_4 + "</p>";
                    html += "<p class='m-0'>" + value.let_txt_5 + "</p>";  
                    html += "<p class='m-0'>" + value.let_txt_6 + "</p>";  
                    html += "<button type='button' class='btn btn-primary' data-bs-toggle='modal' data-bs-target='#edit-employee-modal' id='edit_employee_modal' data-bs-id='"+value.id+"'>Edit</button>";
                    html += '</a>';
                });
                html += '</div>';
            } else {
                html += '<div class="alert alert-warning">';
                  html += 'No records found!';
                html += '</div>';
            }

            

            // Insert the HTML Template and display all employee records
            $("#employees-list").html(html);
        }
    });
}

Я хочу манипулировать html кнопкой но у меня не получается.

html += "<button type='button' class='btn btn-primary' data-bs-toggle='modal' data-bs-target='#edit-employee-modal' id='edit_employee_modal' data-bs-id='"+value.id+"'>Edit</button>";

Как пример помогите мне сделать следующее:

  • При нажатие на кнопку чтобы выводился alert("test");
  • Или edit_employee_modal.style.color = "red";

Моя проблема в том что я не знаю эту ошибку, inspect -> console (при нажатии на кнопку):

modal.js:332 Uncaught TypeError: Cannot read properties of undefined (reading 'classList')
at De._isAnimated (modal.js:332:26)
at De._initializeBackDrop (modal.js:205:24)
at new De (modal.js:82:27)
at De.getOrCreateInstance (base-component.js:55:41)
at HTMLButtonElement.<anonymous> (modal.js:434:22)
at HTMLDocument.n (event-handler.js:120:21)

Что я пробовал?!

let edit_employee_modal = document.querySelector("#edit_employee_modal");
edit_employee_modal.onclick = function() {
    edit_employee_modal.style.color = "red"; 
}

Пробовал выполнить скрипт после загрузки страницы:

window.document.onload = function(e){ 
let edit_employee_modal = document.querySelector("#edit_employee_modal");
    edit_employee_modal.onclick = function() {
        edit_employee_modal.style.color = "red"; 
    }
}

И заменял на код ниже, тоже не получилось (Потому что я думаю, что javascript не может прочитать мои теги):

window.onload = function(e){ 
   //code 
}
document.addEventListener("DOMContentLoaded", function(event) { 
  // code 
});

Можете ли вы помочь мне с любыми идеями?

ps: я новичок не судите строго

5
  • Дело в том что все ваши попытки обратиться к нужной кнопке были после того как DOM был распарсен и до того как кнопка (или любые другие элементы) была вставлена после запроса. Чтобы не париться на счёт того, когда же к кнопке можно обратиться, предлагаю вам с самого начала вставить в вашу вёрстку кнопку (или любые другие элементы), но скрыть, а когда придёт ответ от сервера, от достать эту кнопку (или любые другие элементы) вставить туда ваш текст и слушатель и только после этого их показать
    – EzioMercer
    1 июн 2022 в 8:35
  • Есть и второй способ, вы можете создать всё что вам нужно после ответа сервера, через document.createElement, тогда вы так же сможете вставить любой текст, навесить нужные обработчики событий и в конце все эти элементы вставить в ваш HTML
    – EzioMercer
    1 июн 2022 в 8:37
  • 1
    @eziomercer Первый вариант понравился, не подумал, попробую, спасибо 🙏
    – Sergiu
    1 июн 2022 в 8:45
  • Обратите внимание, что у всех кнопок одинаковый id 1 июн 2022 в 10:10
  • Ну это не значит что скрипт не должен работать, хоть для первой но должен
    – Sergiu
    1 июн 2022 в 10:13

1 ответ 1

1

Не важно каким способом мы получили данные, важно обратиться к элементам (кнопкам) после того, как они добавлены в DOM.

Есть простой дедовский способ, когда мы явно задаем атрибут onclick в подгружаемых данных:

function addButton() {
  buttons.innerHTML += '<button type="button" class="btn-edit" onclick="eventHandler(this)">Edit</button>';
}

function eventHandler(e) {
  e.style.background = 'red';
}
<div id="buttons"></div>
<button onclick="addButton()">Добавить</button>

Если хотите назначить обработчики после добавления HTML, то так и делаете:

function addButton() {
  buttons.innerHTML += '<button type="button" class="btn-edit">Edit</button>';
  attachEvents();
}

function attachEvents() {
  let buttons = document.querySelectorAll('.btn-edit');

  for (let btn of buttons) {
    btn.addEventListener('click', eventHandler);
  }
}

function eventHandler(e) {
  this.style.background = 'red';
}
<div id="buttons"></div>
<button onclick="addButton()">Добавить</button>

В вашем случае, добавить обработчики нужно после $("#employees-list").html(html), ведь метод html() не является асинхронным.

1
  • Спасибо, это сработало
    – Sergiu
    3 июн 2022 в 14:07

Ваш ответ

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

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