jquery根据动态添加的属性选择元素

标签 jquery selector custom-data-attribute

我试图回答这个问题: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)事件:

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");
});

关于jquery根据动态添加的属性选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16943285/

相关文章:

jquery 检索 relatedTarget.data ('url' )值

css - selenium xpath 获取没有关联 id 的元素的值

jquery - 在 jQuery 选择器中定义数组索引

javascript - fadeIn() 不与 delay() 一起工作

jquery - 按名称引用 JSON 对象

python - 为什么我无法使用 scrapy 选择亚马逊页面中的某些元素?

javascript - 如何使用用户输入动态传递数据集属性?

javascript - 根据具有数据属性的类更改宽度/高度

javascript - 为什么这个$.getJSON请求会出错?

javascript - 如何使用 JS 编辑 CSS 变量?