如何为每个post添加eventlistener(不使用jquery)?

eagi6jfj  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(226)

我正在编写一个代码,用户可以在一个帖子标题列表中获取用户帖子。如果用户点击一个帖子标题,那么应该会出现一个新的div框,其中包含更多信息。文章由php获取,文章描述由ajax获取(稍后我将用ajax获取帖子)

**我的问题是:*只有第一个帖子标题有效,点击它,所有的帖子描述都显示在一个div框中。我想我需要一个数组,但尝试它却没有成功。
**它应该做什么:**例如,单击title:2,只显示post2的描述。

记住,文章标题列表是动态的,是从数据库中获取的数据。
这是我的密码:

索引.php

<!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))
      {
          echo "<div class='img_title'><button id='img_descr'><a>Title: <b>".$row['img_title']."</b></a></button></div>";
      }
    ?>
    <div id="descrs"></div>
    <script>
      document.getElementById('img_descr').addEventListener('click', loadDescr);

      function loadDescr(){
        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>

ajax.php文件

<?php
// Create Connection
$conn = mysqli_connect('localhost', 'root', '', 'xy');
$query = 'SELECT * FROM images';
// Get Result
$result = mysqli_query($conn, $query);
// Fetch Data
$users = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($users);
?>

数据库结构/内容:

创建一个名为“xy”的数据库
创建一个名为“images”的表:

CREATE TABLE images (
    img_id int(11) not null AUTO_INCREMENT PRIMARY KEY,
    img_file varchar(250) not null,
    img_title text(50) not null,
    img_descr varchar(250) not null
);

将数据插入数据库:

INSERT INTO images (img_title, img_descr) VALUES ('Golden Retriever', 'UK:DFYDFBAERSDFBYDFBYDFydfbydfBaeydfb1311y');
INSERT INTO images (img_title, img_descr) VALUES ('Appenzeller Sennenhund', 'Swiss:erydfydfbrehaydydfbydfydbaerydf2ydfb');
INSERT INTO images (img_title, img_descr) VALUES ('German Shepard', 'Germany:ydf3d1fby3df1by3dfb6ydfb31ydf31ydf');
INSERT INTO images (img_title, img_descr) VALUES ('Alaskan Klee Kai', 'USA:f3ngxfgxfgnxfxfgnxfg3xf31gnxfgner6ae13')
d6kp6zgx

d6kp6zgx1#

您使用的是同一个id img_descr 所有按钮。这就是为什么它只适用于第一个按钮的事件,而不适用于其他按钮。
尝试对这些按钮或唯一ID使用类。下面是为这些按钮使用公共类的示例。 document.querySelectorAll 将返回所有带有类“imgŠu descr”的按钮作为nodelist(dom node list),这是一种数组类型,您可以使用循环对其进行迭代。您可以在此处使用css选择器。(dot)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>

更新
问题1:我是否必须与“img\u id”合作才能实现这一目标,或者是否有其他方法可以实现这一目标?你想让我开始一个新问题吗?
ans1:id对于所有元素来说都应该是唯一的。通过id,您可以唯一地标识dom中的节点。你可以用 img_id 来自db,它是主键。
问题2:通过单击任何按钮,所有描述都会显示在一起。我需要的是:单击title 1-->get descr 1,单击title 2-->get descr 2等等,动态加载标题列表
答案2:你可以用这种方法来做这件事,尽管有多种方法:

// 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);

希望这有帮助!

相关问题