繁体   English   中英

jQuery onclick事件不适用于链接

[英]jquery onclick event doesn't work for link

我的jsp页面顶部</head>之前有一个脚本。 <a> onclick事件外,其他所有操作均按预期进行。 这是我的代码:

 $(document).ready(function () { $.ajax({ url: 'paging', type: 'GET' }).success(function (data) { $('#pagination').empty(); $.each(data, function (index, user) { $('#pagination').append($('<tr>') .append($('<td>').append($('<a>').attr({ 'onclick': 'GoToProfile(' + user.username + ')' }).text(user.username))) .append($('<td>').text(user.email))) }); $("#sales").dataTable({ "sPaginationType": "full_numbers", "bJQueryUI": true, }); }); }); function GoToProfile(user) { window.location.href = "/profile/" + user; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

当我单击用户名时,为什么GoToProfile函数不起作用? 我把它放在$(document).ready ,outside等里面的不同位置,但是没有用。

我会推荐这种方法,尽管其余的代码编写得并不好。 我没有测试它,但是它应该可以工作。

$(document).ready(function () {
  function GoToProfile(user) {
    window.location.href = "/profile/" + user;
  }
  $.ajax({
    url: 'paging',
    type: 'GET'
  }).success(function (data) {
    $('#pagination').empty();
    $.each(data, function (index, user) {
      $('#pagination').append($('<tr>')
        .append($('<td>').append($(`<a data-username="${user.username}">`).text(user.username)))
        .append($('<td>').text(user.email)))
      });

      $("#sales").dataTable({
        "sPaginationType": "full_numbers",
        "bJQueryUI": true,
      });
   });
  $("#pagination").on("click", "a", function(){
    const $this = $(this);
    GoToProfile($this.attr(data-username));
  });
});

正如斯科特·马库斯(Scott Marcus)所说:

attr({'onclick': 'GoToProfile(' + user.username + ')'}) 

应该更改为

on('click', function(){GoToProfile(user.username)})

令人困惑的一点是,我在项目的其他位置为链接使用了完全相同的语法,并且它们工作得很好。 我只是不知道为什么它在这里不起作用!

暂无
暂无

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

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