jQuery/JavaScript - Allow CTRL + Click to open link in new tab

前端 未结 3 2064
悲哀的现实
悲哀的现实 2021-02-14 02:12

Is there a way in jQuery or JavaScript to enable the user to CTRL + Click a link to open a link in a new tab like example element?

3条回答
  •  滥情空心
    2021-02-14 03:01

    In case anyone wants to disable page navigation on regular click, to make an ajax call or something, but still wants to keep the default ctrl+click and right-click and middle-click(mouse scroll button) , that is the way:

    $('#link').bind('click', function(e) {
      if (!e.ctrlKey && e.which != 2 && e.which != 3) {
        e.preventDefault();
        // some logic:
        $('#box').append('
    ').append($('').html('not paging but doing something! Now try with CTRL')); } });
    
    

    JQuery documentation says:

    event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right. Use event.which instead of event.button.

提交回复
热议问题