javascript preventDefault 不适用于锚点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16772638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:56:22  来源:igfitidea点击:

preventDefault not working on anchor

javascriptjqueryajax

提问by silvdb

I'm trying to log the click on an anchor that's being generated asynchronously.

我正在尝试记录对异步生成的锚点的点击。

The asynchronous call - which works perfectly fine - looks like this:

异步调用 - 工作得很好 - 看起来像这样:

 $("#txt_search").keyup(function() {
    var search = $("#txt_search").val();

    if (search.length > 0)
    {
      $.ajax({
        type: "post",
        url: "<?php echo site_url ('members/searchmember') ;?>",
        data:'search=' + search,
      success: function(msg){
        $('#search_results').html("");
        var obj = JSON.parse(msg);

        if (obj.length > 0)
        {
          try
          {
            var items=[];   
            $.each(obj, function(i,val){                      
                items.push($('<li class="search_result" />').html(
                  '<img src="<?php echo base_url(); ?>' + val.userImage + ' " /><a class="user_name" href="" rel="' + val.userId + '">'
                  + val.userFirstName + ' ' + val.userLastName 
                  + ' (' + val.userEmail + ')</a>'
                  )
                );
            }); 
            $('#search_results').append.apply($('#search_results'), items);
          } 
          catch(e) 
          {   
            alert(e);
          }   
        }
        else
        {
          $('#search_results').html($('<li/>').text('This user does not have an account yet'));   
        }   

      },
      error: function(){            
        alert('The connection is lost');
      }
      });
    }
  });

The anchor I want to get to is <a class="user_name" href="" rel="' + val.userId + '">' + val.userFirstName + ' ' + val.userLastName + ' (' + val.userEmail + ')</a>'

我要到达的锚点是 <a class="user_name" href="" rel="' + val.userId + '">' + val.userFirstName + ' ' + val.userLastName + ' (' + val.userEmail + ')</a>'

I detect the click on these anchors with this function:

我使用此功能检测对这些锚点的点击:

  // click op search results
  $("a.user_name").on('click', function(e) {
    e.preventDefault(); 
  });

The problem seems to be that the preventDefaultis not doing anything... I've looked at most of the questions involving this problem on Stackoverflow and checked jQuery's own documentation on the topic, but I can't seem to find what's wrong. I've tried adding a async: falsestatement to the AJAX-call, because perhaps the asynchronous call might be the problem, but that didn't fix it.

问题似乎preventDefault是没有做任何事情......我已经在 Stackoverflow 上查看了大部分涉及这个问题的问题,并检查了 jQuery 自己关于该主题的文档,但我似乎无法找到问题所在。我尝试async: false在 AJAX 调用中添加一条语句,因为异步调用可能是问题所在,但这并没有解决问题。

回答by Adil

Event does not bind with dynamically added element unless you delegate it to parent element or document using on(). You have to use different form of on for event delegation.

事件不会与动态添加的元素绑定,除非您使用on()将其委托给父元素或文档。您必须使用不同形式的 on 进行事件委托。

$(document).on('click', 'a.user_name', function(e) {
    e.preventDefault(); 
});

delegated events

委托事件

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, Reference

事件处理程序仅绑定到当前选定的元素;当您的代码调用 .on() 时,它们必须存在于页面上。为确保元素存在并且可以被选择,请在文档就绪处理程序中为页面上 HTML 标记中的元素执行事件绑定。如果将新 HTML 注入页面,则在将新 HTML 放入页面后选择元素并附加事件处理程序。或者,使用委托事件附加事件处理程序,如下所述。

委托事件的优点是它们可以处理来自稍后添加到文档的后代元素的事件。通过选择在附加委托事件处理程序时保证存在的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要,参考

回答by nnnnnn

The .on()syntax you showed will only bind handlers to elements that match the selector at that moment- not to elements added in the future. Try this instead:

.on()你教语法仅绑定处理程序来选择匹配的元素在那一刻-不要在将来添加的元素。试试这个:

$("#search_results").on("click", "a.user_name", function(e) {
  e.preventDefault(); 
});

This binds a handler to the parent element, and then when a click occurs jQuery only calls your callback function if the actual target element matches the selector in .on()'s second parameter at the time of the click. So it works for dynamically added elements (as long as the parentexists at the time the above runs).

这会将处理程序绑定到父元素,然后当单击发生时,如果实际目标元素.on()在单击时与 的第二个参数中的选择器匹配,jQuery 只会调用您的回调函数。所以它适用于动态添加的元素(只要在上面运行时元素存在)。

回答by HADI

This should work for you -

这应该适合你 -

$('.search_result').on('click', 'a.user_name', function(){
    // your code here
    // code
    return false;   
});

回答by PSR

try this

试试这个

 $("a.user_name").on('click', function(e) {
    return false;
  });

or

或者

  $(document).on('click', 'a.user_name', function(e) {
      e.preventDefault(); 
          });

Difference between .on() functions calls

.on() 函数调用的区别

回答by Travis Heeter

I had this problem too, and it turned out my selector was wrong.

我也有这个问题,结果我的选择器错了。

回答by Poorna

May be your a href linked with other listeners too. Check with event.preventDefault event.stopImmediatePropagation();together. You can check this site for more info https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

也可能是您与其他听众链接的 href。检查event.preventDefault event.stopImmediatePropagation(); 一起。您可以查看此站点以获取更多信息 https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/