简体   繁体   English

使用JavaScript更改HTML文本区域

[英]Change HTML textarea with JavaScript

I have the following code in the HTML: 我在HTML中有以下代码:

<button onclick="showDescription();">Find book</button>

While in the JavaScript file attached: 在附加的JavaScript文件中:

function showDescription(){
    document.getElementById("description").value="book";
}

However, whenever I click the button, it only shows the string "book" for 1 second, and disappears. 但是,每当我单击该按钮时,它仅显示字符串“ book” 1秒钟,然后消失。 Any idea what went wrong? 知道出了什么问题吗?

Your button is (presumably) inside a <form> . 您的按钮(大概)在<form>

The default type for a button is submit . 按钮的默认类型是submit

  1. The JavaScript runs JavaScript运行
  2. The value is updated 值已更新
  3. The form is submitted 表格已提交
  4. The page is reloaded 页面已重新加载
  5. The initial value is displayed again 初始值再次显示

Don't use a submit button: 不要使用提交按钮:

<button type="button" onclick="showDescription();">Find book</button>

Alternatively, return false from your event handler: 或者,从事件处理程序返回false:

onclick="showDescription(); return false;"

I'm guessing that button is inside a form, change it from : 我猜该按钮在窗体内,将其更改为:

<button onclick="showDescription();">Find book</button>

to: 至:

<input type="button" onclick="showDescription();" value="Find book" />

A button has a default type of submit, so it will submit the form and reload the page if it's inside a form element. 按钮的默认类型为Submit,因此它将提交表单并重新加载页面(如果它位于form元素内)。

Try this code: 试试这个代码:

<!DOCTYPE html>
<html>
    <head>
        <script>
            function showDescription()
            {
                document.getElementById("description").innerHTML="book";
            }
        </script>
    </head>
    <body>

        <button onclick="showDescription();">Find book</button>

        <textarea id="description" rows="4" cols="50">
        </textarea>

    </body>

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

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