javascript - 使用 jquery 追加函数后访问 jquery 元素

标签 javascript php jquery ajax

<分区>

如何获取<a>的点击事件当我访问点击事件时使用 jquery 标记它无法访问请帮助。

这是我使用追加方法添加数据的脚本

$.ajax({
  type: "POST",
  url: URL,
  data: datastring
}).done(function(data) {

  var status = JSON.parse(data);
  for (var i in status) {
    $("#loadmystatus").append(
      "<div style='float: right; margin-top: 5px;'>" +
      "<label style='font-weight: 500;' class='lblsizr'>2:45 am 02/04/2016</label>" +
      "<div class='dropdown user-menu' style='margin-right: 16px;'>" +
      "<button class='iconsiz' id='dd-user-menu' type='button' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
      "<img src='image/icon/menu option.png' alt='' style='height: 6px; margin-left: 8px;'>" +
      "</button>" +
      "<div class='dropdown-menu dropdown-menu-right' aria-labelledby='dd-user-menu'>" +
      "<a class='make dropdown-item' name='make' id='make'>" +
      "<span class='font-icon glyphicon glyphicon-thumbs-up'></span>" +
      "Make current status" +
      "</a>" +
      "<a class='dropdown-item' href='#'>" +
      "<span class='font-icon glyphicon glyphicon-remove'></span>" +
      "Remove" +
      "</a>" +
      "</div>" +
      "</div>" +
      "</div>" +
      "<br>" +
      "<div style='border-radius: 10px;'>" +
      "<label>" + status[i].userstatus + "</label>" +
      "</div>" +
      "<hr>"
    );
  }
});

这是我用来访问标签的脚本,甚至没有用

<script type="text/javascript">
$(document).ready(function()
{
   $('#make').on('click', function(event) {
   alert("hello");
});
});

请帮帮忙

最佳答案

您将事件处理程序附加到尚未创建的元素。

要解决您的问题,您可以按照 Sergio 在评论中的建议将事件处理程序附加到 document#loadmystatus

$(document).on('click', '#make', function(event) {
   alert("hello");
});

$('#loadmystatus').on('click', '#make', function(event) {
   alert("hello");
});

$(document).on("click", "#make", function(e){alert('test')});
$("#loadmystatus").append("<button id='make'>Click me!</button>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loadmystatus"></div>

关于javascript - 使用 jquery 追加函数后访问 jquery 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41756916/

相关文章:

javascript - GWT:在页面准备好之前开始运行(或者正文资源不阻止运行 gwt)?

javascript - 从 iframe 更改父 url

javascript - 在悬停时相互切换的元素

javascript - 无法使用 .not() 或 :not properly

php - Zend Framework 2 - 数据库连接

javascript - PHP - 更新后编辑元素消失了

php - 使用更改鼠标坐标的 JQuery/Ajax 通过 post/get 传递变量到另一个文件

php - Memcached PHP 模块 : How can you tell if the connection failed?

php - 使用 PDO 对 null 调用成员函数 query()

javascript - 从json文件获取数据并使用jquery/ajax显示值