javascript - .click 未在按钮上注册

标签 javascript jquery html

<分区>

我在无序列表中的一些文本之后呈现了这个按钮:

enter image description here

按钮的 HTML 是这样的:

<a 
    data-action="remove" 
    data-class-name="ECEC 301 Advanced Programming for Engineers Lab"    
    class="btn btn-danger remove-item btn-xs btn-font-12-px btn-raised margin-add-to-cart mdi-content-remove-circle-outline">
</a>

这是它所在的无序列表元素:

enter image description here

我正在尝试编写一些在单击按钮时调用操作的 jQuery,但无论我写什么,我都无法注册单击操作,例如:

$('.btn.btn-danger.remove-item').on('click', function(){
    console.log("you should see this");
});


    $("[data-action]").click(function() {
        console.log("yeah");
    });


    $('a[data-action="remove"]').click(function() {
        console.log("yeah");
    });

编辑:按钮是在页面加载后使用 jQuery 动态创建的(我调用我的 JSON API 来创建类的无序列表)

最佳答案

由于按钮是动态生成的,因此您需要使用 event delegation

$(document).on('click','.btn.btn-danger.remove-item', function(){
    console.log("you should see this");
});

Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future.

取自:http://learn.jquery.com/events/event-delegation/

关于javascript - .click 未在按钮上注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32152580/

相关文章:

html - CSS - 悬停时文本 move

javascript不会执行嵌套的for循环

javascript - 追加 div 元素,然后使用 JQUERY 从右到左设置动画

javascript - Ionic 将 firebase 注入(inject)工厂,同时将 Controller 和服务保存在不同的文件中

jquery - 提交按钮到相关页面

jquery - Google map v3 - 更新拖动标记

html - 我们可以给 li 分配宽度吗

javascript - 基于正则表达式匹配启用 javascript/jquery 中的按钮

javascript - 如何使用 Javascript 不循环 JSON 中已有的键

javascript - 为任何聚焦元素触发按键点击事件