1

我试图回答这个问题:Find specific anchor tag and replace data attribute on click,我创建了这个 jsfiddle ,它试图根据数据属性选择一个锚元素。

我想根据特定的数据属性在此锚点上捕获事件。

<a href="#" class="article-play" data-play="4">click</a>

JS

//this event only fires if 'data-pause' is initially specified in the anchor element
$(".article-play[data-pause]").on("click", function() {
    $(this).removeAttr("data-pause");
    $(this).attr("data-play",4);

    $("#output").text("playing 4");
});

//this event only fires if 'data-play' is initially specified in the anchor element
$(".article-play[data-play]").on("click", function() {
    $(this).removeAttr("data-play");
    $(this).attr("data-pause",3);

    $("#output").text("pausing 3");
});

这是预期的行为吗?jQuery中的错误?还有什么?

4

2 回答 2

2

因为在绑定处理程序时您的元素不在 DOM 中,所以您需要委托事件:

http://jsfiddle.net/BjkQT/8/

$(".article").on("click", ".article-play[data-pause]", function () {
    $(this).removeAttr("data-pause");
    $(this).attr("data-play", 4);

    $("#output").text("playing 4");
});

$(".article").on("click", ".article-play[data-play]", function () {
    $(this).removeAttr("data-play");
    $(this).attr("data-pause", 3);

    $("#output").text("pausing 3");
});
于 2013-06-05T15:06:31.223 回答
1

如果您要动态更改元素,则需要使用委托

$('parentelement').on('click','.article-play[data-pause]',function(){
    $(this).removeAttr("data-pause");
    $(this).attr("data-play",4);

    $("#output").text("playing 4");
});

$('parentelement').on('click','.article-play[data-play]',function(){
    $(this).removeAttr("data-play");
    $(this).attr("data-pause",3);

    $("#output").text("pausing 3");
});

jQuery live 记录了.live()的替换

$(选择器).live(事件、数据、处理程序); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(事件、选择器、数据、处理程序); // jQuery 1.7+

它显示了与文档的绑定,因为这就是 live 的工作方式 - 但最好将处理程序绑定到选择器的静态父元素

您可以在jQuery .on() 文档中阅读更多相关信息

于 2013-06-05T15:06:08.707 回答