我試圖回答這個問題:Find specific anchor tag and replace data atribute on click和我創建this jsfiddle它試圖根據數據屬性選擇一個錨元素。jquery select元素根據屬性動態添加
我想基於特定的數據屬性在此錨上捕獲事件。
<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中的錯誤?還有別的嗎?
它的預期。它在添加屬性之前評估選擇器,因此與它不匹配。 –
我不禁想到原來的問題OP是做錯了...... – Alnitak
@CJ S.我以爲'on'是爲了替代'live',它允許我們綁定動態元素 – Jason