简体   繁体   English

preventDefault无法锚定

[英]preventDefault not working on anchor

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 preventDefault is 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. 问题似乎是preventDefault没有做任何事情......我在Stackoverflow上查看了大部分涉及这个问题的问题,并检查了jQuery自己关于该主题的文档,但我似乎无法找到错误。 I've tried adding a async: false statement to the AJAX-call, because perhaps the asynchronous call might be the problem, but that didn't fix it. 我已经尝试在AJAX调用中添加async: false语句,因为可能异步调用可能是问题,但是没有修复它。

Event does not bind with dynamically added element unless you delegate it to parent element or document using on() . 除非使用on()将事件委托给父元素或文档,否则事件不会与动态添加的元素绑定。 You have to use different form of on for event delegation. 您必须使用不同的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(). 它们必须存在于您的代码调用.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. 要确保元素存在且可以选择,请在文档就绪处理程序内对页面上HTML标记中的元素执行事件绑定。 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. 如果将新HTML注入页面,请在将新HTML放入页面后选择元素并附加事件处理程序。 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 通过挑选这是保证出席委派的事件处理程序连接时的元素,你可以使用委托的事件,以避免需要频繁安装和取下事件处理程序, 参考

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. .on()语法,你表现只会结合处理程序来选择的那一刻匹配的元素-而不是在将来添加的元素。 Try this instead: 试试这个:

$("#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. 这会将处理程序绑定到父元素,然后当发生单击时,如果实际目标元素与单击时.on()的第二个参数中的选择器匹配,则jQuery仅调用您的回调函数。 So it works for dynamically added elements (as long as the parent exists at the time the above runs). 因此它适用于动态添加的元素(只要父节点在上面运行时存在)。

This should work for you - 这对你有用 -

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

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()函数调用之间的区别

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

May be your a href linked with other listeners too. 也可能是你与其他听众联系的href。 Check with event.preventDefault event.stopImmediatePropagation(); 检查event.preventDefault event.stopImmediatePropagation(); together. 一起。 You can check this site for more info https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/ 您可以访问此站点以获取更多信息https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM