簡體   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