2014-10-01 119 views
1

我在同一頁上有一些不同的項目,每個項目都有一個註釋部分。我的目標是在有人在文本框中寫入內容時獲取輸入ID,但是當我調用文本框的ID時,它始終返回相同的ID,我的意思是不明白它是哪個輸入。Jquery使用相同的名稱獲取正確的元素ID?

我的代碼;

對於實施例

的Item1

<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; 
    } 
    }); }); 

我如何理解哪些輸入被按下?

謝謝...

回答

1

簡單,你可以使用this

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

它不應該是 「$(本).ID」 獲得當前元素id? – Sasse 2014-10-01 08:36:30

+0

@Sasse不,你可以使用更多的方式.. $(this)[0] .id – Balachandran 2014-10-01 08:37:40

+0

或$(this).attr(「id」) – xwcg 2014-10-01 08:43:55