JS Always getting the same event object “e” parameter with mousedown

问题: I'm trying to handle a middle mouse button click event with JQuery on a DataTable (https://datatables.net/). Here is my code. var tbl = document.getElementById("entries")...

问题:

I'm trying to handle a middle mouse button click event with JQuery on a DataTable (https://datatables.net/). Here is my code.

var tbl = document.getElementById("entries");
$(tbl).on('mousedown', function (e) { 
     e.preventDefault();
     if (e.which == 2) {
         var table = window.table_entries;
         var data = table.dataTable.row($(e.detail)).data();
         window.open("/plugin/Changes/@Model.Revision/" + data.BuildId, '_blank');
     }
});

I'm always getting the same BuildId (284), no matter where I click. How can I get the correct row?

I also have another code snippet, which works perfectly fine

tbl.addEventListener("cdt.click", function (e) {
        var table = window.table_entries;
        var data = table.dataTable.row($(e.detail)).data();
        window.open("/plugin/Changes/@Model.Revision/" + data.BuildId, '_blank');
        window.location("/plugin/Changes/@Model.Revision/" + data.BuildId);
 });

Thanks in advance!


回答1:

if you want to check de middle button click with jquery check this code

$("#foo").on('click', function(e) { 
  if( e.which == 2 ) {
  e.preventDefault();
  alert("middle button"); 
  }
});

From this question Triggering onclick event using middle click

And if you want to check downmouse you can check this other @KyleMit answer Detect middle button click (scroll button) with jQuery


回答2:

@Jordi Jordi (because I can't comment right now) : Based on JQuery's documentation, click & mousedown both works.

$('h1').on('mousedown', function(e) {
    alert(e.which);
});

Will display 1 for LClick, 2 for Middle, 3 for RClick. But this isn't the question. If you're getting the same BuildId, it's because your selector isn't the good one.

If you're searching to get an exact row, you should change your selector like this :

$('td').on('mousedown', function (e) { 
    e.preventDefault();
    if (e.which == 2) {
        // Here you should get the row like this :
        var row = $(this).parent();
    }
});

Now it's your job to do what you want with this. The var "row" will contain the TR, meaning the row you just give a click.

EDIT : Note that your second code snippet doesn't include e.preventDefault(). Maybe it's the reason this second one works ?

  • 发表于 2019-03-15 14:01
  • 阅读 ( 167 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除