繁体   English   中英

单击以通过jQuery AJAX从PHP加载的html元素不起作用

[英]Click to html element loaded from PHP through jQuery AJAX won't work

我有一个页面,当单击按钮时,将显示带有“ id”属性的表,该表是使用jQuery AJAX和php加载的。 并且在我的JavaScript中,将click事件放置到表格单元格将不起作用。

这是我的完整代码。 希望您能够帮助我。

dynamic_table.html

 <!DOCTYPE html> <html> <head> <title></title> <style> table, th, td { border: 1px solid black; } th, td { padding: 15px; } td.filled { background-color: red; } td.unfilled:hover{ background-color: blue; cursor: pointer; } </style> </head> <body> <button id="avail_seat_button" type="button">Show Available Seats</button> <div id="table_avail_seat"> <!-- the table will appear here --> </div> <br /> <input type="number" id="seat_no"> <script src="js/jquery-1.11.3.min.js"></script> <script src="js/handy_script.js"></script> <script src="js/available_seats.js"></script> </body> </html> 

available_seats.js

 $(document).ready(function(){ $("#avail_seat_button").click(function(){ $date_departure = "2017-10-22"; $time_departure = "6:30 AM - 10:30 AM"; $route = "Sagay-Cebu Via Tolido"; $.ajax({ type: "POST", url: "available_seats.php", data: { date_departure: $date_departure, time_departure: $time_departure, route: $route } }).done(function(result){ $("#table_avail_seat").html(result); }); }); }); 

代码片段形式Reservation.php类

 $cell = 0; for ($row = 1; $row <= 9; $row++) { echo "<tr>"; for ($col = 1; $col <= 5; $col++) { $cell++; if (in_array($cell, $array_seats)) { //mark as not available echo "<td class='filled'>"; echo $cell; echo "</td>"; } else { //mark as available echo "<td class='unfilled'>"; echo $cell; echo "</td>"; } } echo "</tr>"; } 

handy_script.js

 $(document).ready(function(){ $("td.unfilled").on("click", function() { alert("hello world"); }); }); 

available_seats.php

 <?php include "php_library/SiteBasics.php"; include "php_library/Reservation.php"; $reservation = new Reservation; $reservation->available_seats(); ?> 

对于动态生成的元素,必须使用jQuery.on("click", function() {}); 而不是使用.click()

有关更多详细信息,请参见下面的链接

为什么要使用jQuery on()而不是click()

我在这里自己解决了问题。 就我而言,可以在我的Reservation.php代码中添加onclick =“”属性。 但这仍然是我的问题,为什么.click()或.on()在我的JavaScript中不起作用。

这是我对Reservation.php代码的修订:

 $cell = 0; for ($row = 1; $row <= 9; $row++) { echo "<tr>"; for ($col = 1; $col <= 5; $col++) { $cell++; if (in_array($cell, $array_seats)) { //mark as not available echo "<td class='filled'>"; echo $cell; echo "</td>"; } else { //mark as available echo "<td class='unfilled' onclick=\\"alert('hello')\\">"; echo $cell; echo "</td>"; } } echo "</tr>"; } 

您是否尝试过放置此功能

$("td.unfilled").on("click", function() {
    alert("hello world");
  });

里面的ajax成功替换了html,或者您可以简单地替换它

$("td.unfilled").on("click", function() {
        alert("hello world");
      }); 

有了这个

 $(document).on('click', 'td.unfilled', function(){
  alert("hello world");
      });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM