繁体   English   中英

使用JavaScript更改HTML文本区域

[英]Change HTML textarea with JavaScript

我在HTML中有以下代码:

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

在附加的JavaScript文件中:

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

但是,每当我单击该按钮时,它仅显示字符串“ book” 1秒钟,然后消失。 知道出了什么问题吗?

您的按钮(大概)在<form>

按钮的默认类型是submit

  1. JavaScript运行
  2. 值已更新
  3. 表格已提交
  4. 页面已重新加载
  5. 初始值再次显示

不要使用提交按钮:

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

或者,从事件处理程序返回false:

onclick="showDescription(); return false;"

我猜该按钮在窗体内,将其更改为:

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

至:

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

按钮的默认类型为Submit,因此它将提交表单并重新加载页面(如果它位于form元素内)。

试试这个代码:

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