简体   繁体   English

提醒this.id关键字返回未定义的Javascript

[英]Alerting the this.id keyword returns undefined Javascript

I create the same inputbox a couple of times dynamically. 我动态创建了相同的输入框几次。 When a user presses enter it calls a function. 当用户按下Enter键时,它将调用一个函数。 I then test with this code: 然后,我用以下代码进行测试:

function insertComment(){
  alert($(this).attr('id'));
}

But it keeps returning undefined. 但是它总是返回未定义的。 Here is the syntax I use to create similiar input boxes: 这是我用来创建类似输入框的语法:

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

Just pass this while calling method : 只需在调用方法时传递此方法:

$("#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')); 
}

Beware of this . 当心this It is a crazy variable and you always, always want to think twice before adding it in your code. 这是一个疯狂的变量,您始终希望在将其添加到代码中之前三思而后行。

Before we debug, the first lesson is - 在进行调试之前,第一课是-

  • Every function is always called in a context and if you can't tell the context, it is the window object. 每个函数总是在上下文中调用,如果您不能告诉上下文,它就是window对象。

Now let's breakdown what's going on here. 现在让我们分解一下这里发生的事情。

When a user presses a key on your input field, insertComment is called. 当用户按下输入字段上的键时,将调用insertComment Since there is no context, it is called on the window context. 由于没有上下文,因此在窗口上下文上调用它。 So now, inside the function, your this is actually pointing to window , and there's no window.attr('id') defined. 所以,现在,在函数内部,你this实际上是指向window ,而且也没有window.attr('id')定义。

It is equivalent to calling window.insertComment where this == window . 它等效于在其中this == window调用window.insertComment

If you modify your code like so - 如果您这样修改代码-

onkeydown='if (event.keyCode == 13) insertComment(this)'

function insertComment(x){
    alert(x.attributes.id);
}

Here, the context will still be window , ie this variable will still point to window object, but the input element itself will be passed as a parameter to the insertComment function. 在这里,上下文仍将是window ,即this变量仍将指向window对象,但是input元素本身将作为参数传递给insertComment函数。

x will refer to the element and you can now pull the id attribute in good old fashioned javascript way - x.attributes.id x将引用该元素,您现在可以按老式的javascript方式提取id属性x.attributes.id

(or in jQuery way, if you prefer - $(x).attr('id') ) (或者以jQuery的方式,如果您愿意- $(x).attr('id')

Check this: 检查一下:

HTML: HTML:

<div id="divToAppend">
  <input class="formatCSS" type="text" id="id_1">  

</div>

js & jquery js和jquery

// For alert the ID
 function insertComment(id){
   alert(id);
}

$(document).ready(function(){
// Look for any event 'keydown' in any element which has a class 'formatCSS'
$(document).on('keydown','.formatCSS',function(e){

    // If enter is pressed
    if (e.keyCode == 13){

        //Get the current ID
       var text_id=$(this).attr('id');

        //Split it to get the counter. The ID must be unique
       var id=text_id.split('_');

        //Add 1 to the counter
       var counter=parseInt(id[1])+1;

        // Build the new ID
       var new_text_id="id_"+counter;         

        // Then, create the new input with the iD           
       $("#divToAppend").append("<input id='"+new_text_id+"' type = 'text' class = 'formatCSS' />"); 

        // Last, alert the ID
        insertComment(new_text_id);


    }

});


});

Maybe it can help. 也许可以帮上忙。 :) :)

See it working: http://jsfiddle.net/pN8P6/ 看到它正常工作: http : //jsfiddle.net/pN8P6/

Do you need to store the value in the ID? 您需要将值存储在ID中吗? (it seems that part of your problem might be that you've got multiple identical ids, which is illegal.) (问题的一部分可能是您有多个相同的ID,这是非法的。)

How about: 怎么样:

$("#divToAppend")
  .append("<input type = 'text' class = 'formatCSS' style = 'margin-top:12px ; ' placeholder = 'Add Comment'></input>")
  .keydown(function() { insertComment('whatever') });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM