将数据传递给jQuery click()函数

我有一个简单的跨度

Remove 

此跨度位于表中,每行都有一个删除范围。

然后,当点击该跨度时,我使用AJAX调用URL。 AJAX事件需要知道该行的对象的ID吗? 将该ID放入点击function的最佳方法是什么?

我以为我可以做这样的事情

 Remove 

但ID不应该以数字开头? 对? 然后我想我能做到

 Remove 

然后从ID中删除“我的”部分,但这似乎只是Yuk!

以下是我的点击事件以及我的AJAX事件所在的位置。

  $(document).ready(function() { $(".removeAction").click(function() { //AJAX here that needs to know the ID } });  

我相信有一个很好的方法吗?

注意:我不是在寻找

 $(this).attr("id"); 

我希望能够传递多条信息

谢谢。 杰克。

如果您坚持使用旧式HTML 4.01或XHTML:

 $('.removeAction').click(function() { // Don't do anything crazy like `$(this).attr('id')`. // You can get the `id` attribute value by simply accessing the property: this.id; // If you're prefixing it with 'my' to validate as HTML 4.01, you can get just the ID like this: this.id.replace('my', ''); }); 

顺便说一句,在HTML5中, id属性可以以数字开头,甚至可以是数字 。

再说一次,如果你还在使用HTML5,你可能最好使用自定义数据属性,如下所示:

 Remove 

单击函数中的$(this)表示单击的元素

 $(".removeAction").click(function() { //AJAX here that needs to know the ID alert($(this).attr('id')); } 

以下代码将为您提供所单击span的ID。 使用ID并不完美,但它会起作用。

 $(".removeAction").click(function() { alert($(this).attr("id")); }); 

您可以在每一行上有一个隐藏字段,用于存储JSON对象中所需的ID和/或其他数据,并使用该字段而不是使用span标记进行黑客攻击。

   Remove    $('.removeAction').click(function(){ var id = $(this).next().val(); // do something... }); 

HTH

您可以尝试jQuery.data(): http ://api.jquery.com/jQuery.data,但这意味着服务器端生成的js代码在页面加载时执行,以便您可以存储ID以供以后重用(你的删除行动)

 // this part would have to be server 'generated' // and by that I'm referring to the '' $('table .remove').each(function(){ var MyElem = $(this); MyElem.data('id',  ); MyElem.click(function(){ the_id = $(this).data('id'); // ajax call goes here }); });