2010-08-20 62 views
0

如果我有以下形式的id:t_*其中*可以是任何文本,我如何捕獲這些id的click事件並能夠將*的值存儲到變量中供我使用?jquery捕獲選定ID的文本

+0

請注意我對接受的答案和執行的評論,在使用拆分時不起作用。 – 2010-08-20 13:03:06

回答

3

使用開始與選擇^=這樣的:

$('element[id^="t_"]').click(function(){ 
    alert($(this).attr('id')); 
}); 

element可以是任何元素如divinput或任何你指定你甚至可以離開了這一點:

$('[id^="t_"]').click(function(){ 
    alert($(this).attr('id')); 
}); 

更新:

$('[id^="t_"]').click(function(){ 
    var arr = $(this).attr('id').split('_'); 
    alert(arr[1]); 
}); 

更多信息:

+0

謝謝,這會提醒完整的't_ *'字符串。我怎樣才能得到*? substr(1); – aeq 2010-08-20 12:40:41

+0

$(this).attr('id')。substr(1); – jpluijmers 2010-08-20 12:43:24

+0

@aeq:請參閱我的更新。 – Sarfraz 2010-08-20 12:44:40

0
var CurrentID = $(this).attr('id'); 
var CurrentName = CurrentID.replace("t_", ""); 

這應該有助於repalce。

+0

replace(「t_」,「」);不能使用id爲「t_myidt_endit」,因爲這給出「myidendit」而不是「myidt_endit」 – 2010-08-20 13:00:52

0

試試這個:

// handle the click event of all elements whose id attribute begins with "t_" 
$("[id^='t_']").click(function() 
{ 
    var id = $(this).attr("id"); 

    // handle the click event here 
}); 
+0

答案的一半,沒有獲得id屬性的字符串。 – 2010-08-20 13:04:06

0
$("[id^='t_']").click(function() 
{ 
    var idEnding = $(this).attr("id"); 
    idEnding.replace(/\t_/,''); 

}); 

使用click事件帽確定以t_開始的ID,然後將其替換爲沒有任何結果爲捕獲ID值的結尾。