Jquery使用调用相同名称获取正确的元素id

Jquery Getting correct element id with calling same name?

本文关键字:获取 id 元素 调用 Jquery      更新时间:2023-09-26

我在同一页上有一些不同的项目,每个项目都有一个注释部分。我的目标是当有人在文本框中写东西时获得输入id,但当我调用文本框的id时,它总是返回相同的id,我的意思是它不知道是哪个输入。

我的代码;

例如

第1项

<div id="<?php echo $row['id']; ?>" >
            <div  class="form-group">
                <input type="text"  name="commentbox"  id="<?php echo $row1['id']; ?>" >
              </div>
    </div>

第2项

<div id="<?php echo $row['id']; ?>" >
            <div  class="form-group">
                <input type="text"  name="commentbox"  id="<?php echo $row2['id']; ?>" >
              </div>
    </div>

Jquery;

$(document).ready(function(){
   $("input[name = 'commentbox']").keypress(function (e) { if (e.which == 13) {
     var id=$("input[name = 'commentbox']").attr('id');
        ................
   return false;   
   }
    });  });

我如何理解按下了哪些输入?

谢谢。。。

只需使用this 即可获得当前元素id

$("input[name = 'commentbox']").keypress(function (e){
    console.log(this.id); 
  //$(this)[0].id;
   //$(this).prop("id");      
});