在按键时检索文本区域的 ID

Retrieve textarea's id on keypress

本文关键字:区域 ID 文本 检索      更新时间:2023-09-26

textareakeypress时,我需要选择id并将其分开。这怎么可能?

如果我有一些jQuery代码:

$(document).on("keypress", "textarea", function(){$(this). 

我怎样才能获得textareaid并将其分开,就像idid="ta1"

假设您只对 ID 的数值部分感兴趣,您可以使用 replace() 函数使用正则表达式轻松去除所有非数字字符:

$('textarea').keypress(function(){
     // Get your ID
     var id = $(this).attr('id');
     // Strip off any non-numeric values
     var idNumber = id.replace(/'D+/g, ''); 
});

工作示例

$('textarea').keypress(function() {
  // Get your ID
  var id = $(this).attr('id');
  // Strip off any non-numeric values
  var idNumber = id.replace(/'D+/g, '');
  alert('<textarea> #' + idNumber + ' was typed in');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>Text Area 1</pre>
<textarea id='ta1'></textarea>
<hr />
<pre>Text Area 2</pre>
<textarea id='ta2'></textarea>
<hr />
<pre>Text Area 3</pre>
<textarea id='ta3'></textarea>

试试这个

$('body').on('keypress','textarea',function(){
var id = $(this).attr('id')
var ta = id.substring(0,2);
var num = id.substring(2);
});