简体   繁体   English

innerHTML javascript更改

[英]innerHTML javascript changing

I am trying to make this code work, I want the innerHTML to be changed but It's instantly changing and gets back to its initial state . 我正在尝试使此代码正常工作,我希望更改innerHTML ,但它会立即更改并返回其初始状态。 Any help ? 有什么帮助吗?

<!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>

Your form is getting submitted. 您的form正在提交。 Add a return false; 添加return false; to your button onclick event. 到您的按钮onclick事件。

<button onclick="click_me(); return false;">Edit</button>

Or, make the button type='button' (This is the better option) 或者,将button type='button' (这是更好的选择)

<button onclick="click_me();" type='button'>Edit</button>

The reason is because the button type is submit by default if a type is not specified . 原因是因为如果未指定 type则默认情况下submit按钮type

From MDN , 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. 如果未指定属性,或者该属性动态更改为空或无效值,则这是默认设置。

<!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();return false;">Edit</button></td>
        </tr>
      </table>
    </form>
  </body>
</html>

added a return false statement to the onclick event. 在onclick事件中添加了return false语句。 without it, the form gets submitted and the page reloads 没有它,表单将被提交并重新加载页面

jsfiddle here jsfiddle 在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM