-4

onclick関数を複数回呼び出すことに問題があります。問題は、同じ ID を使用していることですが、2 回目の呼び出しで関数を再利用できるようにしたいということです。これが私がこれまでに持っているものです:

<p onclick='myfunction()'> Click this text for input box  below </p>
<b id='myThing'>input box appears .. ta daa</b>
<p onclick='myfunction()'> Click this new text for input box below </p>
<div id='myThing'> but no input box appears here, the line above must turn this text into a  textbox, but it doesn't because of similar id, how do i fix the id problem without defining a new id over and over?</div>
<script>
  function myfunction(){
    document.getElementById("myThing").innerHTML='<input type="text"/>';
  }
</script>

ID を Javascript 変数に変換する方法はありますか? パーツに入力ボックスを作成させるにはどうすればよいですか?

4

2 に答える 2

1

この場合、div を取得するために ID を使用する必要はありません。

function myfunction(){
 this.nextSibling.innerHTML='<input type="text"/>';
 }
于 2012-11-28T07:15:11.053 に答える
0

あなたはこれを行うことができます:

<p onclick='myfunction("myThing")'> Click this new text for input box below </p>
<script>
function myfunction(id){
 document.getElementById(id).innerHTML='<input type="text"/>';
 }
 </script>

デモンストレーション

全体をよりシンプルにすることもできることに注意してください。単純に id を使用せず、関数に次の要素を検索させます。

<p onclick='myfunction(this)'> Click this text for input box  below </p>
<b>input box appears .. ta daa</b>
<p onclick='myfunction(this)'> Click this new text for input box below </p>
<div> but no input box appears here, the line above must turn this text into a  textbox, but it doesn't because of similar id, how do i fix the id problem without defining a new id over and over?</div>

​&lt;script>
function myfunction(element){
    do {
        element = element.nextSibling;
    } while (element && element.nodeType != 1);
    element.innerHTML='<input type="text"/>';
 }
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

デモンストレーション

于 2012-11-28T07:11:51.223 に答える