Can't get ID of 'this' variable

Can't get ID of 'this' variable

本文关键字:this variable of Can get ID      更新时间:2023-09-26

所以我有一个在$(document).ready(function() { //.....// });内部的jquery事件。它的代码如下:

$('.puzzle_cells').keyup(function(event) {
});

我需要做的下一件事是获得<input>元素的ID与类'puzzle_cells'(顺便说一句,每个<input>与类'puzzle_cells'有一个ID)。自然我会使用this变量,但我不知道如何把它变成一个jquery的.attr('id')函数。

为了确保它清晰,我需要'的id。

输入的"Puzzle_cells"

UPDATE:对不起大家,实际上它不是<input> s有id,而是父<td>为每个人做了。所以,我把我的代码从$(this).attr('id');切换到$(this).parent('td').attr('id');,现在它可以工作了。我不能真正尝试this.id,因为父母的事情,但我确信它的工作。

$('.puzzle_cells').keyup(function(event){
   this.cellID = event.srcElement.id;
});

不太熟悉JQuery,但应该可以。

你可以这样得到它,不是吗?

$('.puzzle_cells').keyup(function(event) {
  var id = this.id; // or $(this).attr('id')
});

不确定为什么需要"以jquery的方式"使用它。它可以工作,就像你说的与this.id

但如果真的需要:

$('.puzzle_cells').keyup(function (event) {
    console.log($(this).attr('id'));
});

就像使用其他元素一样使用$(this).attr("id")

$('.puzzle_cells').keyup(function(event) {
   console.log($(this).attr("id"));
});

JSfiddle