Вы используете один и тот же идентификатор img_descr
для всех кнопок. Поэтому он будет работать только для события первой кнопки, а не для других.
Попробуйте использовать класс для этих кнопокили уникальные идентификаторы.Ниже приведен пример использования общего класса для этих кнопок.document.querySelectorAll
вернет все кнопки с классом «img_descr» как NodeList (список узлов DOM), который является видом массива, вы можете перебирать его с помощью цикла. Вы можете использовать CSS-селекторы. (Точка) class / # for (id)здесь.
Вот пример, он работает на моем компьютере.надеюсь, что это работает и у вас !!
<!DOCTYPE html>
<html>
<head>
<title>XY</title>
<meta charset="UTF-8" />
</head>
<body>
<?php
$db = mysqli_connect("localhost", "root", "", "xy");
$result = mysqli_query($db, "SELECT * FROM images");
while ($row = mysqli_fetch_array($result)) {
// changed <button id='img_descr'> to <button class='img_descr'>
echo "<div class='img_title'><button class='img_descr'><a>Title: <b>" . $row['img_title'] . "</b></a></button></div>";
}
?>
<div id="descrs"></div>
<script>
// Get the buttons (NodeList)
var buttons = document.querySelectorAll("button.img_descr");
console.log(buttons); // debugging in JS!! press F12, see console tab!
for(var x=0; x < buttons.length; x++) {
buttons[x].addEventListener('click', loadDescr);
}
// getElementById returns only one element with the id passed as input
// which is the first found node with the id in the DOM.
// document.getElementById('img_descr').addEventListener('click', loadDescr);
function loadDescr(e) {
// here e is the event and you can get the source of the event(button) by
// e.target target. Here target would be the button that you clicked.
console.log(e.target.innerHTML); // use console.log() very often in JS code!
var xhr = new XMLHttpRequest();
xhr.open('GET', 'ajax.php', true);
xhr.onload = function() {
if (this.status == 200) {
var descrs = JSON.parse(this.responseText);
var output = '';
for (var i in descrs) {
output += '<ul>' +
'<li class="ajax_img_descr">ID: ' + descrs[i].img_descr + '</li>' + '</ul>';
}
document.getElementById('descrs').innerHTML = output;
}
}
xhr.send();
}
</script>
</body>
</html>
ОБНОВЛЕНИЕ
Q1: Нужно ли работать с "img_id", чтобы достичьчто или есть другой, чтобы сделать это?Вы хотите, чтобы я начал новый вопрос для этого?
Ans1: ID - это то, что всегда должно быть уникальным для всех элементов.С помощью идентификатора вы можете однозначно идентифицировать узел в DOM.Вы можете использовать img_id
из DB, который является первичным ключом.
Q2: все описания отображаются все вместе, нажав любую кнопку.Что мне нужно, это: Нажмите заголовок 1 -> получить дескриптор 1, нажмите заголовок 2 -> получить дескр 2 и так далее, и так далее, и список заголовков загружается динамически
Ans2: Вы можете сделать это, используя этот способ, хотя есть несколько способов сделать это:
// 1.1 PHP Change
while ($row = mysqli_fetch_array($result)) {
// changed <button id='img_descr'> to <button class='img_descr' id=row's id column>
echo "<div class='img_title'><button class='img_descr' id="$row['id']"><a>Title: <b>" . $row['img_title'] . "</b></a></button></div>";
}
// 1.2 JS change
function loadDescr(e) {
...
console.log(e.target.innerHTML); // use console.log() very often in JS code!
let id = e.target.getAttribute('id'); // get the ID of element, e.target.id also does the same
var xhr = new XMLHttpRequest();
xhr.open('GET', 'ajax.php?img='+id, true); // append the id in query
...
}
// 1.3 PHP ajax.php change
// check if the query has id passed
if (isset($_GET['img'])) {
$id = $_GET['img'];
// change the query to find by id
$query = "SELECT * from images where img_id=$id";
} else {
$query = "SELECT * from images";
}
$result = mysqli_query($conn, $query);
// Fetch Data
$users = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($users);
Надеюсь, это поможет!