警告this.id关键字返回未定义的Javascript

use*_*875 1 javascript jquery html5 dynamic inputbox

我动态地创建了几次相同的输入框.当用户按下enter键时,它会调用一个函数.然后我用这段代码测试:

function insertComment(){
  alert($(this).attr('id'));
}
Run Code Online (Sandbox Code Playgroud)

但它一直未定义返回.这是我用来创建类似输入框的语法:

$("#divToAppend").append("<input id='testID' type = 'text' class = 'formatCSS' style = 'margin-top:12px ; ' placeholder = 'Add Comment' onkeydown='if (event.keyCode == 13) insertComment()'></input>");
Run Code Online (Sandbox Code Playgroud)

Vic*_*ves 7

只需在调用方法时传递:

$("#divToAppend").append("<input id='testID' type = 'text' class = 'formatCSS' style = 'margin-top:12px ; ' placeholder = 'Add Comment' onkeydown='if (event.keyCode == 13) insertComment(this)'></input>");


function insertComment(this)
{ 
alert($(this).attr('id')); 
}
Run Code Online (Sandbox Code Playgroud)