2014-12-05 56 views
0

我有一個具有某個ID的元素,我更改了它的ID,當我單擊該元素(現在使用新的ID)時,它仍然調用前一個函數IDJQuery-更改一個元素的ID並在點擊時調用一個函數

$('#1st').click(function(){ 
 
    $('#1st').attr('id','2nd'); 
 
    alert("id changed to 2nd"); 
 
}); 
 
$('#2nd').click(function(){ 
 
    alert("clicked on second"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<a href="javascript:;" id="1st">Click</a>

實施例是here

+0

ALWA這個帖子ys在問題中發佈相關代碼。 – 2014-12-05 21:05:43

+0

小提琴連接 – baig772 2014-12-05 21:06:11

+0

我無法打開鏈接... – 2014-12-05 21:06:48

回答

2

因爲你的元素存在之前添加事件。它沒有找到一個元素。請在更改ID時附加事件,或者需要使用事件委派。

$('#1st').on("click.one", function(e) { 
 
     $('#1st').attr('id', '2nd'); 
 
     alert("id changed to 2nd"); 
 
     e.stopPropagation(); 
 
     $(this).off("click.one"); 
 
    }); 
 
    $(document).on("click", '#2nd', function() { 
 
     alert("clicked on second"); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<a href="#" id="1st">Click</a>

+0

謝謝,它的工作:) – baig772 2014-12-05 21:13:35

+0

當他可以使用更好的授權時,這是很多額外的qork如fermis提議的那樣 – SpYk3HH 2014-12-05 21:17:11

1

嘗試做這種方式jsFiddle

$(document).on('click', '#2nd', function(){ 
 
\t \t alert("clicked on second"); 
 
\t }) 
 
\t .on('click', '#1st', function(e) { 
 
\t \t $('#1st').attr('id','2nd'); 
 
\t \t alert("id changed to 2nd"); 
 
\t });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<a href="#" id="1st">Click</a>

詳情可參見Jquery's .on() versus .click()

相關問題