preventDefault在锚点上不起作用 [英] preventDefault not working on anchor

查看:94
本文介绍了preventDefault在锚点上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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');
      }
      });
    }
  });

我想到达的锚点是<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(); 
  });

问题似乎是preventDefault没有做任何事情...我已经在Stackoverflow上查看了涉及此问题的大多数问题,并查看了该主题的jQuery自己的文档,但我似乎无法找出问题所在.我尝试在AJAX调用中添加async: false语句,因为也许异步调用可能是问题所在,但这并不能解决问题.

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. 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.

推荐答案

除非您使用

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.

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

委托事件

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

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

这篇关于preventDefault在锚点上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆