简体   繁体   English

使用 JQuery/JS 在 click() 上存储 a 的 id

[英]Using JQuery/JS to store the id of a <td> on click()

I have a table with a bunch of data.我有一张包含一堆数据的表格。 Each <td> contains class="person" and id=0,1,2,3, etc. based on $i (I'm using a loop to build my table from an array).每个<td>包含基于$iclass="person"id=0,1,2,3, etc. (我使用循环从数组构建表)。

I'd like it so that whenever a person ( <td> ) is clicked, that cell gets highlighted with some css.我希望这样每当一个人( <td> )被点击时,那个单元格就会被一些 css 突出显示。

So far I think I can use this:到目前为止,我认为我可以使用这个:

$('.person').click(function(){ $('.person').click(function(){

 $id = some function to which attr('id') was selected???; $('id').addClass("highlights");

}); });

Does anyone know how I can fetch the ID of the cell being clicked?有谁知道我如何获取被点击的单元格的 ID? Any help or approaches appreciated.任何帮助或方法表示赞赏。

Thanks!谢谢!

this.id refers to the id of the td inside the method. this.id指的是方法内部的tdid

$('.person').click(function(){

    var id = this.id;
    $('#' +id).addClass("highlights");

});

But if you want to just change something on the element, then you do not really need the id .但是,如果您只想更改元素上的某些内容,那么您实际上并不需要id That is because the this keyword refers to the actual clicked element.那是因为this关键字是指实际点击的元素。

So you can directly do所以你可以直接做

$('.person').click(function
    $(this).addClass("highlights");
});

Beware, though, that the id of an element cannot be numeric ( as far as valid html is concerned.. )但请注意,元素的 id不能是数字有效的 html而言..

And i quote我引用

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). IDNAME标记必须以字母 ([A-Za-z]) 开头,后跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_") , 冒号 (":") 和句点 (".")。

$('.person').click(function(){

$(this).addClass("highlights");

});

Sometimes, you can forget about id in jQuery:)有时,您可能会忘记 jQuery 中的 id :)

$("td").click(function(e){

alert($(this).attr('id'));
e.stopPropagation();
});

here is the working fiddle http://jsfiddle.net/xELyx/1/这是工作小提琴http://jsfiddle.net/xELyx/1/

also have a look at jquery id selectors http://api.jquery.com/id-selector/也看看 jquery id 选择器http://api.jquery.com/id-selector/

and

attr http://api.jquery.com/attr/ attr http://api.jquery.com/attr/

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

Seems to be the line you want:)似乎是你想要的线:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM