-4

我多次调用onclick函数时遇到问题。问题是我使用的是相同的 ID,但我希望能够在第二次调用中再次重用该函数。这是我到目前为止所拥有的:

<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

在这种情况下,您不需要使用 ID 来获取 div。

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 回答