2011-09-28 19 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... 
}); 
相关问题