2013-07-08 12 views
0

我通過循環在JavaScript中動態創建的多個文字區域。我做到了「只讀」,現在使用的字符串,我想,只要點擊任何文本區域的功能應該是call.Now這個功能我想顯示點擊textarea的值設置不同的值。現在,我需要點擊textarea的ID。我通過textarea.id得到它,但它顯示了動態創建的textareas的最後一個id。就好像我創建了15個textareas然後獲得id它顯示了我的第15個id。獲取動態創建文本域的IDS

var div = document.createElement("div"); 
div.setAttribute("style","margin-left:10px;width:750px;height:180px;background-image:url(images/questions_option_bg_2.png);position:relative;margin-top:15px"); 

textarea = document.createElement("textarea"); 
textarea.setAttribute('id', "textid"+i); 
textarea.setAttribute('readonly', 'readonly'); 
textarea.setAttribute("cols",35); 
textarea.setAttribute("rows",5); 
textarea.setAttribute("style","overflow:hidden;color: white; font-size: 30px;margin-left:10px;position:relative;margin-top:5px;background:transparent;border:thin;outline:none;"); 
textarea.value=all_sel_questions[(question_shuffled_array[i])]; 

div.appendChild(textarea); 
$("#third_div").append(div); 
textarea.addEventListener('click', clickonTextArea, false); 

function clickonTextArea() 
{ 
    var value=textarea.id; 
    alert(value); 
} 
+2

'textarea'在函數'clickonTextArea'是從周圍的範圍(且因此保持到最後*分配值的基準。*)也許一個本地事件處理程序定義'this'?如果不是,請考慮使用jQuery綁定單擊事件。 – jensgram

回答

1

使用this方面

function clickonTextArea(e) { 
    var value=this.id; 
    // OR 
    // var value = e.target.id; 
    alert(value); 
} 

textarea持有引用到已綁定到最後文本區域。所以它總是指向你創建的最後一個實例。

0

你的事件函數應該是這樣的......

function clickonTextArea(e) 
{ 
    var e = e || window.event; 
    var ta = e.target || e.srcElement; 

    var value=ta.id; 
    alert(value); 
} 
1

您可以通過this訪問目標文本區域的事件處理程序。

function clickonTextArea(event) { 
    var value = this.id; 
    alert(value); 
} 
相關問題