簡體   English   中英

提醒this.id關鍵字返回未定義的Javascript

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

我動態創建了相同的輸入框幾次。 當用戶按下Enter鍵時,它將調用一個函數。 然后,我用以下代碼進行測試:

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

但是它總是返回未定義的。 這是我用來創建類似輸入框的語法:

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

只需在調用方法時傳遞此方法:

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

當心this 這是一個瘋狂的變量,您始終希望在將其添加到代碼中之前三思而后行。

在進行調試之前,第一課是-

  • 每個函數總是在上下文中調用,如果您不能告訴上下文,它就是window對象。

現在讓我們分解一下這里發生的事情。

當用戶按下輸入字段上的鍵時,將調用insertComment 由於沒有上下文,因此在窗口上下文上調用它。 所以,現在,在函數內部,你this實際上是指向window ,而且也沒有window.attr('id')定義。

它等效於在其中this == window調用window.insertComment

如果您這樣修改代碼-

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

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

在這里,上下文仍將是window ,即this變量仍將指向window對象,但是input元素本身將作為參數傳遞給insertComment函數。

x將引用該元素,您現在可以按老式的javascript方式提取id屬性x.attributes.id

(或者以jQuery的方式,如果您願意- $(x).attr('id')

檢查一下:

HTML:

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

</div>

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


    }

});


});

也許可以幫上忙。 :)

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

您需要將值存儲在ID中嗎? (問題的一部分可能是您有多個相同的ID,這是非法的。)

怎么樣:

$("#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