jquery onclick事件不适用于链接

问题描述 投票:1回答:2

我在</head>之前的jsp页面上有一个脚本。一切都按预期工作,除了<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,外面等等,但没有奏效。

javascript jquery jsp
2个回答
0
投票

我会推荐这种方法,虽然其余的代码编写得不是很好。我没有测试它,但它应该工作。

$(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));
  });
});

0
投票

正如斯科特马库斯所说:

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

应该改为

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

令人困惑的是,我在项目的其他地方对我的链接使用了完全相同的语法,并且它们运行得非常好。我只是不知道为什么它在这里不起作用!

© www.soinside.com 2019 - 2024. All rights reserved.