简体   繁体   English

PreventDefault不适用于动态链接

[英]PreventDefault not working for dynamic link

<a href="#" class="submit-form show-field" data-show-field="#Product" >View products</a>

This link is dynamically added to the dom, and I fire a jQuery function on click 此链接是动态添加到dom的,点击时会触发jQuery函数

$('body').on("click", 'a.show-field', function(e) {
    if (!$(this).attr('data-show-field')) { 
        return; 
    }
    $($(this).attr('data-show-field')).parent().show();
    e.preventDefault();    
});

The event fires fine, but page redirects. 事件触发正常,但页面重定向。 I cant understand what I've done wrong 我不明白我做错了什么

You event is fired before you can prevent it. 您必须先触发事件,然后才能阻止它。

$('body').on("click", 'a.show-field', function(e) {

    e.preventDefault();  

    if (!$(this).attr('data-show-field')) { 
        return; 
    }
    $($(this).attr('data-show-field')).parent().show();  
    /*e.preventDefault();  */
});

If the page redirects then I think your listener is not working well. 如果页面重定向,那么我认为您的监听器运行不正常。 Here you are a plunker with a use case. 在这里,您是一个具有用例的小伙伴。 With and whithout document ready 准备好文件

I don´t know where you put your code, but if it's outside the "document ready" that listener never fires. 我不知道您将代码放在哪里,但是如果它不在“文档准备就绪”之外,则侦听器永远不会触发。

$('body').on("click", 'a.show-field', function(e) {
  alert("First attemp is attached");
});

$(document).ready(function() {
  $('body').on("click", 'a.show-field', function(e) {
    alert("Second attemp is attached");

    if (!$(this).attr('data-show-field')) {
      return;
    }

    $($(this).attr('data-show-field')).parent().show();
    e.preventDefault();
  });
});

PD: sorry for my english PD:对不起,我的英语

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

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