2011-09-28 16 views
1

您能否建議我如何處理多個錨點標記以獲得點擊功能?如何區分jQuery中id爲多個錨點標籤的onclick樂趣

我的代碼是這樣的:

<a id="test1" href="#" >test1</a> 
<a id="test2" href="#" >test2</a> 

我jQuery的功能是:

$('a').click(function(event) { 
    alert('click'); 
}); 

jQuery的點擊功能適用於所有錨標籤,但我想區分基於jQuery開發功能id屬性 ..

回答

1

你可以得到id attrib UTE。

$('a').click(function(event) { 
    alert($(this).attr('id')+' clicked!'); 
}); 
1

您可以閱讀元素的ID並根據ID使您的功能

$('a').click(function(event) { 
    if ($(this).attr("id") == 'test1') 
    { 
     alert('Test 1 was clicked'); 
    } 
    else if ($(this).attr("id") == 'test2') 
    { 
     alert('Test 2 was clicked'); 
    } 
}); 
2

你想幹什麼取決於ID不同的東西?

你可以做類似

$('a').click(function(e){ 
    var id = $(this).attr('id'); 
    // switch depending on id 
}); 

OR

$('#test1').click(function(e){ alert("you clicked test1"); }); 
$('#test2').click(function(e){ alert("you clicked test2"); }); 

但這不會是非常好的,如果你再要添加多的做同樣的事情。

1

如果你希望綁定到基於ID的元素:

$('#test1').click(function(event) { 
    alert('test1 clicked'); 
}); 
5

看這個id和做if語句或交換機(建議使用開關):

$('a').click(function(event) { 
    switch(this.id) { 
     case 'test1': 
      alert('link with an id of test1!'); 
      event.preventDefault(); 
      break; 
     case 'test2': 
      alert('link with an id of test2!'); 
      event.preventDefault(); 
      break; 
     default: 
      //Default behavior 
    } 
}); 
+0

你是快! :) xaxa:D –

1

這是我的方法

$('a').click(
    function() 
    { 
     switch($(this).attr('id')) 
     { 
      case 'test1': 
       // Do some work 
       break; 
      case 'test2': 
       // Do some work 
       break; 
     } 
    } 
); 
0

你可以看看在其他答案中建議的id,但你也可以附加數據屬性每個標籤都具有自定義數據屬性(html5)或使用href,以後可以通過onclick事件(html5)訪問它。

樣本:

<a id="test1" data-my-custom-data="Insert" data-row-id="24" href="#" >test1</a> 
<a id="test2" href="Insert" >test2</a> 

$("a").click(function(event) 
{ 
    alert($(this).attr("data-my-custom-data")); 
    alert($(this).attr("data-row-id")); 
    alert($(this).attr("href")); 

    event.preventDefault(); // To avoid browsing to href... 
}); 
相關問題