'.在'单击“不运行”功能

'.on' click not running function?

本文关键字:不运行 功能 运行 单击      更新时间:2023-09-26

我有一个函数,当它运行时,会动态生成新的标记。。。

$('.search input[type="image"]').on('click', function(){
    // Open directions in a map
    if($('#TXT_SAddr').val() === ''){
        return false;
        $('.directions .search').css('background' , '#ff0000'); 
    } else {
        var from = $('#TXT_SAddr').val();
        var to = $('.postal-code').html();
        var directions = 'http://maps.google.com/maps?saddr=' + from + '&daddr=' + to + '&output=embed';
        var modal = '<div class="apply-modal modal"><a class="close-apply-now" style="margin-bottom: 20px;"><img src="http://site.co.uk/images/closeModal.png" alt="Close" style="border-width:0px;"></a><div class="holder"><iframe src="'+directions+'" style="border:none; width:100%; height:500px;" border="0"></iframe></div></div>';
        $('body').prepend('<div class="modalOverlay"/>' + modal);
        $('.modal').animate({
                'opacity': 1,
                'top': '100px'
            }, 700, 'easeOutBack');
    }
    return false;
});

如果您可以看到,上面生成了一个div,该div的类名为"close-apply-now",并带有一个锚点。

我现在想将一个函数绑定到这个,我已经尝试使用。。。

$('a.close-apply-now').on('click', function(){
    alert('asdasd');
});

运气不好的话,有人能看出我哪里出了问题吗?甚至我的警报都不起作用。

由于close-apply-nowdiv是动态添加的,因此需要使用event delegation来注册事件处理程序,如:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('body').on('click', 'a.close-apply-now', function(event) {
    event.preventDefault();
    alert('asdasd');
});

这将把您的click事件附加到body元素中类关闭立即应用的任何锚点上。

事件委派的语法略有不同。

事件需要绑定到dom中已经存在的元素,而目标元素选择器需要作为第二个参数传递

$(document).on('click', 'a.close-apply-now', function(){
    alert('asdasd');
});

close-apply-nowdiv是动态添加的。您必须添加选择器参数,否则事件将直接绑定(不适用于动态加载的内容),而不是委托。看见http://api.jquery.com/on/#direct-和委托事件

将代码更改为

$(document.body).on('click', '.update' ,function(){

jQuery集接收事件,然后将其委托给与给定参数的选择器匹配的元素。这意味着,与使用live时相反,执行代码时必须存在jQuery集合元素。

使用jQuery的live()方法。描述:为现在和将来与当前选择器匹配的所有元素附加一个事件处理程序。

$("a.close-apply-now").live("click", function(){
  alert('asdasd');
});

在Jsfidle 中同时尝试