2012-01-23 56 views
0

爲了使文本「可編輯」,我寫了一個函數,它用輸入元素(step1)替換文本,後來(onchange)用輸入值替換文本-lelement(step2)Javascript onchange - 點擊未定義

這有效,除了以下情況:如果輸入元素處於活動狀態(程序的第1步),並且在輸入元素中單擊,則(在輸入元素中)文本被替換爲「不確定」,功能不能正常工作更多的

<html> 
<head> 

<title>Test</title> 

<script type="text/javascript"> 
<!-- 

// global variables for use in (out-of-function) listeners 
var changeText_actual; 
var changeText_parent; 

function changeText(actual) { 
    // element representing a textNode 
    changeText_actual = actual; 
    // element containing the textNode 
    changeText_parent = actual.parentNode; 

    // create a new html-element to input text 
    var textfield = window.document.createElement("input"); { 
     textfield.setAttribute("type", "text"); 
     // text in textNode 
     textfield.setAttribute("value", actual.data); 
     // listener for when user has finished input (e.g. by pressing return) 
     textfield.setAttribute("onchange", 
      // if inputText is not empty 
      "if(this.value && this.value.length > 0) {" 
       // fill textNode with inputText 
      +" changeText_actual.data = this.value;" 
      +"}" 
      // remove input-element and put textNode inplace 
      +"changeText_parent.replaceChild(changeText_actual, this);" 
     ); 
    } 

    // remove textNode and put input-element inplace 
    changeText_parent.replaceChild(textfield, changeText_actual); 
    // select inputText for faster editing 
    textfield.select(); 
} 

//--> 
</script> 

</head> 
<body> 

<table border="1"><tr> 
<th>1. Text</th><th onclick="changeText(this.firstChild)">2. Text</th><th>3. Text</th> 
</tr><tr> 
<td>4. Text</td><td>5. Text</td><td>6. Text</td> 
</tr></table> 

</body> 
</html> 

我只是尋求比解決一個解釋,因爲我覺得能夠解決此問題的工作,如果我知道,「未定義」來自哪裏(並且我可以捕捉到它)

+0

只需使用'contentEditable',例如' lolwat' –

回答

1

1 \第一次單擊< th>元素時,它的第一個子元素是文本節點。它的數據屬性是「2.文本」。所以當你引用this.firstChild時,它是一個文本節點。

2 \將使用textnode作爲參數調用changeText函數,因此「actual」將是文本節點。

然後,您將文本節點更改爲文本框。

3 \當你點擊文本框,這是父母的onclick處理程序被再次執行(該<日>的onclick),但這個時候,this.firstChild是< input>標記,所以功能會用輸入元素作爲參數調用。參數「actual」將是一個輸入元素。 輸入元素沒有屬性稱爲數據,因此在該行

textfield.setAttribute("value", actual.data); 

的actual.data是未定義的。

這是回答你的問題,但我覺得給自己澄清一些事情:

您可以實際使用textfield.onclick =函數(){} .....寫一個函數,它是一個更安全的方式。

使用onchange將文本框更改回文本並不總是可以打開的(例如,如果你不想改變任何東西),你應該檢查元素是否失去焦點(模糊)。

+0

哦,我認爲你誤解了我的問題;我會編輯它,所以它更清晰 – Hachi

+0

好吧,我已經寫了一個簡短的發生了什麼事。 – SoonDead

+0

啊我忘了冒泡;所以一個檢查actual.data是否有用;非常感謝 – Hachi