2014-05-16 62 views
-2

我试图获取动态生成的表的id属性。所以,如果我点击第一个链接,我想获得“editEmploee-4”。jQuery获取链接ID

<table id="example" class="table span12 table-bordered table-hover"> 
    <thead> 
     <tr> 
     <th>Firstname</th> 
     <th>Lastname</th> 
     <th>Edit</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
     <td>Person 1</td> 
     <td>Name Person 1</td> 
     <td><a href="#" class = "editDialog" id="editEmployee-4"><img src="img/edit.png" height="20" /></a></td> 
     </tr> 
     <tr> 
     <td>Person 2</td> 
     <td>Name Person 2</td> 
     <td><a href="#" class = "editDialog" id="editEmployee-5"><img src="img/edit.png" height="20" /></a></td> 
     </tr> 
     <tr> 
     <td>Person 3</td> 
     <td>Name Person 3</td> 
     <td><a href="#" class = "editDialog" id="editEmployee-47"><img src="img/edit.png" height="20" /></a></td> 
     </tr> 
    </tbody> 
</table> 

我试过这个代码,但我总是得到相同的ID。

var data = $("a[id][class=editDialog]").attr('id'); 

你有什么想法如何获得动态生成的链接ID?

+0

你什么时候这样做?在'onclick'处理程序中? –

回答

5

事件委托:

$(document).on("click", "#example a", function() { 
    console.log(this.id); //id of clicked link 
}); 

不知道有多少表是动态生成的,但你通常要使用的容器元素,而不是document

2

可以使用this.id的点击处理程序中的主播:

$('.editDialog').click(function() { 
    var data = this.id; 
}); 

但是因为你的表是动态生成的,所以所有的事件对这个表和它里面的元素都是不可用的,在这种情况下你需要应用事件委托技术来附加这些事件,比如点击你的情况到这些新的添加的元素:

$(document.body).on("click", "#example a", function() { 
    var data = this.id; 
}); 

实际上,它会在绑定委派的事件到最近的静态父,而不是$(document)更有效率。

5
$(".editDialog").click(function(e) 
{ 
    e.preventDefault(); 
    var myID = $(this).attr("id"); 
// do something with myID 
}) 
+1

为什么选择jQuery?为什么不'this.id'? –

+0

@ Karl-AndréGagnon习惯的力量我猜:) – andrew

+0

这些都是坏习惯:) –

0

正如我们在所有的标签类“editDialog”。我们可以在我们的jQuery或Java脚本代码中使用此:

的JQuery ::

$('.editDialog').bind('click', function(){ 
alert($(this).attr('id')); 
}); 

Java脚本::

$('.editDialog').bind('click',function(){ 
var clickedID = this.id; 
alert(clickedID); 
});