javascript - 我的链接未触发点击事件,如何修复?

标签 javascript jquery

我正在基于我收到的 JSON 数据在 FLY 上创建几个链接(使用 jQuery html 函数)。每个链接都有 id“idxxxx”(xxxx 是主键)。

这是我正在使用的 JavaScript 代码:

$(document).ready(function(){
    onLoad();

    $("a[id^=id]").on("click", function(event) {
        alert('here');
    });

    function onLoad() {
        $(document).prop("title", "Course Listing");

        getCourses();
    }

    function getCourses(name) {
        $.ajax({
            url: "http://localhost/courses/getCourses?format=json"
            , dataType: "json"
            , data: {name: name}
            , success: function(data, status) {
                populateCourses(data);
            }
        });
    }

    function populateCourses(data) {
        var html = "";

        if (data.length > 0) {
            $.each(data, function () {
                html += "<a href='##' id='id" + this.ID + "'>Edit</a><br />";
            });
        }

        $("#courselist").html(html);
    }
});

我的问题是创建的链接不会触发点击事件。

作为测试,我在页面上手动创建了一个链接标记,其 ID 与其他链接类似,但我没有遇到同样的问题。警报框显示正常。

关于如何解决这个问题有什么想法吗?谢谢

最佳答案

试试这个:

$(function() {
  var ar = [];
  for (var i = 1; i <= 10; i++) {
    ar.push("<a href='#' id='id" + i + "'>Link " + i + " </a>");
  }

  $("#courselist").html(ar.join(''));

  //THIS WILL ADD CLICK HANDLER TO ANY A INSIDE div#courselist
  //EVEN IF IT IS ADDED AT RUNTIME
  $("#courselist").on("click", "a[id^='id']", function(event) {
    $("#log").append($("<span/>").text($(this).text()));
  });
});
a {
  margin: 2px;
  padding: 3px;
  outline: none;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
     </script>
<div id="courselist"></div>
<div id="log"></div>

关于javascript - 我的链接未触发点击事件,如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27537475/

相关文章:

javascript - 我的 Ajax 代码只从 Mysql 数据库行中获取一行的值

c# - XML API 子项返回函数?

javascript - 检测多个异步 javascript $.ajax 调用的完成

javascript - 如何在特定情况下突出显示事件导航选项卡

javascript - 调整大小功能无法正常工作

javascript - 从AngularJS中嵌套的ng-repeat内的下拉选项中获取选定的值

javascript - 如何使用 node-mongodb-native 连接到 Modulus.io?

javascript - Lodash - 搜索字符串是否包含以开头的单词

javascript - 如何设置正确的 src 路径(GET localhost 获取 404(未找到))?

javascript - 方法中的默认变量?