2013-06-05 130 views
1

我試圖回答這個問題: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中的錯誤?還有別的嗎?

+0

它的預期。它在添加屬性之前評估選擇器,因此與它不匹配。 –

+1

我不禁想到原來的問題OP是做錯了...... – Alnitak

+0

@CJ S.我以爲'on'是爲了替代'live',它允許我們綁定動態元素 – Jason

回答

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

$(selector).live(events, data, handler);    // jQuery 1.3+ 
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+ 
$(document).on(events, selector, data, handler);  // jQuery 1.7+ 

因爲這是如何生活的作品就說明結合到文件 - 但最好將處理程序綁定到選擇器的靜態父元素

您可以在此處閱讀jQuery .on() documentation