2012-01-23 1 views
0

テキストを「編集可能」にするにはテキストを入力要素(step1)以降に置き換えて(onchange)テキストを入力値に置き換える関数を作成しました-element(step2)JavaScript onchange - クリック時に未定義になる

以下のシナリオを除いて、これは機能します:input要素がアクティブで(前の手順1)、input要素をクリックすると、(input要素内の)テキストが「未定義」と機能が正しく、私はこの問題を回避作業することを感じるので、私ならば、私は単に、ソリューションよりも説明を求める

<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 \ <番目の要素を初めてクリックすると、最初の子がテキストノードになります。データ属性は「2.テキスト」です。だからthis.firstChildを参照すると、それはテキストノードです。

2 \関数changeTextはtextnodeをパラメータとして呼び出されるため、「実際」はテキストノードになります。

次に、テキストノードをテキストボックスに変更します。

3 \テキストボックスをクリックすると、親のonclickハンドラが再度実行されますが(<>のonclick)、今回はthis.firstChildが<入力>タグなので、関数は入力要素をパラメータとして呼び出されます。パラメータ「実際」は入力要素になります。 actual.dataが定義されていないライン

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

におけるよう 入力要素は、いかなる属性と呼ばれるデータを有していません。

あなたの質問への答えですが、私はいくつかのことを明確にする衝動を感じる:

あなたが実際にある関数を記述するために(){...} textfield.onclick =機能を使用することができますはるかに安全な方法。

テキストボックスをテキストに戻すためにonchangeを使用することは、必ずしも満足できるとは限りません(たとえば、何かを変更したくない場合など)。要素がフォーカスを失っているかどうかを確認する必要があります(ぼかし)。

+0

ああ、私はあなたが私の質問を誤解したと思う。私はそれを編集するので、より明確です – Hachi

+0

OK、私は何が起こるかの簡単なウォークスルーを書いています。 – SoonDead

+0

ああ、私は泡立つことを忘れてしまった。実際のデータのチェックがそのトリックを行います。ありがとうございます。 – Hachi