我试图回答这个问题:Find specific anchor tag and replace data atribute on click我创建了this jsfiddle它尝试根据数据属性选择 anchor 元素。
我想根据特定的数据属性捕获此 anchor 上的事件。
<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 中的错误?还有别的吗?
最佳答案
因为在绑定(bind)处理程序时您的元素不在 DOM 中,所以您需要委托(delegate)事件:
$(".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");
});
关于jquery根据动态添加的属性选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16943285/