我正在尝试使此代码正常工作,我希望更改 innerHTML
但它会立即更改并返回到其初始状态。有什么帮助吗?
<!DOCTYPE html>
<html>
<head>
<script>
function click_me(){
alert('fdsfs');
var tweety=document.getElementById('text_this').innerHTML;
alert(tweety);
var text_area="<input type=text value='"+tweety+"'>";
alert(text_area);
document.getElementById('text_this').innerHTML=text_area;
}
</script>
</head>
<body>
<form name="form1">
<table border=1>
<tr>
<td>
<div id="text_this">123</div>
</td>
<td>
<button onclick="click_me();">Edit</button>
</td>
</tr>
</body>
</html>
最佳答案
您的表单
正在提交。将 return false;
添加到按钮 onclick
事件。
<button onclick="click_me(); return false;">Edit</button>
或者,使按钮type='button'
(这是更好选项)
<button onclick="click_me();" type='button'>Edit</button>
原因是,如果type
未指定,按钮type
默认为submit
。
来自MDN ,
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
关于javascript - 改变innerHTML javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19067018/