我多次调用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变量?如何使零件创建输入框?
答案 0 :(得分:1)
在这种情况下,您不需要使用ID来获取div。
function myfunction(){
this.nextSibling.innerHTML='<input type="text"/>';
}
答案 1 :(得分: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>
<script>
function myfunction(element){
do {
element = element.nextSibling;
} while (element && element.nodeType != 1);
element.innerHTML='<input type="text"/>';
}
</script>