2

我正在努力在页面上的一系列跨度标签之后动态添加带有点击事件处理程序的链接。该链接正在添加到页面中,但单击时事件处理程序未触发。Web 控制台中没有记录错误。我确信我在下面的代码中遗漏了一些明显的东西:

function changeClicked (e) {
    e.preventDefault();
    console.log('should work');
}

function initChangeOwner() {
    var changeLink = $('<a />', {
        href: '#',
        text: 'change',
        'class': 'changeLink',
        click: changeClicked
    });

    var licenseFor = $('[id*="LicenseFor"]').after(changeLink);
}

$(document).ready(function () {
    initChangeOwner();
    // other inits
});

为什么我的点击事件处理程序没有触发?对于那些喜欢摆弄的人,我在 jsFiddle 上设置了一个示例

* 这是一个使用 jQuery 1.4.1 的旧应用程序。不幸的是,现在不是将引用更新到新版本的时候。

4

4 回答 4

4

在您的特定情况下,无需花哨的动态绑定。看到您在添加元素时处于控制之中,并且您当时想要绑定事件,您可以在附加元素后单独绑定单击事件。

function initChangeOwner() {
    var changeLink = $('<a />', {
        href: '#',
        text: 'change',
        'class': 'changeLink'
    });

    var licenseFor = $('[id*="LicenseFor"]').after(changeLink);

    // Now the elements exist and you can bind the click event using the 'changeLink' class as a selector.
    $(".changeLink").click(function(event){changeClicked(event);});

}

DEMO - 创建元素后绑定

于 2012-08-31T17:19:14.557 回答
2

重组你的代码,如:

function initChangeOwner() {
    $('[id*="LicenseFor"]').each(function(){
        var changeLink = $('<a />', {
            href: '#',
            text: 'change',
            'class': 'changeLink',
            click: changeClicked
        });
       $(this) .after(changeLink);
    });
}

http://jsfiddle.net/xUjTd/48/这工作正常

我认为问题在于首先将一个事件附加到 changeLink,然后将其多次插入 DOM。http://jsfiddle.net/xUjTd/60/

于 2012-08-31T17:22:36.283 回答
2

通常我会说使用.on(),但看起来你正在使用 jQuery 1.4.4。

像这样为点击添加一个.live()事件:这一切都有效:

$('.changeLink').live('click', function (e) {
   changeClicked(e); 
});

看起来在 1.4.4 中存在某种错误,因为您无法将这些 click / onclick 属性添加到元素中。(附带说明::无论如何,您都不想在元素上使用click/onclick/onmouseover/etc,每个单独(每个元素)在IE中创建一个脚本文件(降低性能)。它看起来也像你原来的代码在更高版本的 jQuery 中工作,只是在 1.8 中尝试过它工作正常。

此外,return false;在您的 changeClicked() 函数中使用(它对您都有作用stopPropagation & preventDefault,之后的任何内容都不会运行,以及href="#"锚点的属性。

function changeClicked(e) {
    console.log('here we are');

    return false; // stops link - preventDefault & stopPropagation
    console.log('it WONT get here');
}

jsFiddle 演示

于 2012-08-31T17:15:06.047 回答
1

函数应该是这样的:

function initChangeOwner() {
  $('[id*="LicenseFor"]').each(function(index){
    var changeLink = $('<a />', {
    href: '#',
    text: 'change',
    'class': 'changeLink',
     click: changeClicked
   });

    $(this).after(changeLink);
  });
}

工作演示

于 2012-08-31T17:22:28.863 回答