【问题标题】:I can't get my added element to activate a function我无法让我添加的元素来激活功能
【发布时间】:2013-01-31 03:20:46
【问题描述】:

我正在尝试在创建colorbox 接口时添加一个链接。它最终将链接到当前显示的图像文件,但现在我只想让 console.log 工作。它正确添加了链接(#print-one),但是单击链接时我无法运行函数。任何帮助将不胜感激!

$(document).bind('cbox_complete', function () {
    // Show close button with a delay.
    $('#cboxClose').css('opacity', 1);
    // Add Print Button
    if ($('#print-one').length ) {
        // Do Nothing
    }else {
        $('#cboxNext').after('<a href="javascript:void(0)" id="print-one">Print</a>');
    }
});

$('#print-one').click(function() {
    console.log('Works');
});

这一切都包含在 $(document).ready 函数中。单击链接时,我无法使控制台日志正常工作。我一直在用头撞墙试图弄清楚。感谢您的帮助!

【问题讨论】:

  • 如果将$('#print....).click 移动到else 中会怎样?

标签: onclick colorbox insertafter


【解决方案1】:

您需要委托该事件。

$(document).on('click', '#print-one', function(){});

【讨论】:

  • 这非常有效!我曾尝试过与此类似但不起作用的方法,但我有 #print-one 你有文档。感谢您的帮助!
【解决方案2】:

好像是cbox初始化之后才添加链接的,编译器到下面几行的点击绑定函数可能还没准备好。

试试这个:

...
// Add Print Button
if ($('#print-one').length ) {
    // Do Nothing
}else {
    $('<a href="#">Print</a>').insertAfter('#cboxNext').click(function() {
        console.log('Works');
    });
}

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 2016-12-28
    • 1970-01-01
    • 2022-06-15
    • 2011-02-03
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多