我如何设置我的网页以接受文本字段的输入,并将其用作页面上的新文本

How do I set up my webpage to take input from a text field and use it as new text on the page?

本文关键字:文本 新文本 字段 设置 何设置 我的 网页 输入      更新时间:2023-09-26

我正在尝试制作一个可以作为闪存卡使用的网络应用程序,但我需要能够将用户键入的内容输入到教科书中并将其添加到页面中。以下是我发现的内容,但我希望嵌入文本。

<!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
 <title>textBoxes.html</title>
 <script type = "text/javascript">
  // from textBoxes.html
  function sayHi(){
  var txtName = document.getElementById("txtName");
  var txtOutput = document.getElementById("txtOutput");
  var name = txtName.value;
  txtOutput.value = "Hi there, " + name + "!"
  } // end sayHi
 </script>
 <link rel = "stylesheet"
   type = "text/css"
   href = "textBoxes.css" />
 </head>
 <body>
 <h1>Text Box Input and Output</h1>
 <form action = "">
  <fieldset>
  <label>Type your name: </label>
  <input type = "text"
    id = "txtName" />
  <input type = "button"
    value = "click me"
    onclick = "sayHi()"/>
  <input type = "text"
    id = "txtOutput" />
  </fieldset>
 </form>
 </body>
</html>

查看AngularJS。它可以做你想做的事。还有更多!

var app = angular.module('app', []);
app.controller('AppCtrl', function($scope) {
  $scope.name = "";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppCtrl">
  <input type "text" placeholder="Enter your name" ng-model="name" />
  <h3>Hello<span ng-show="name">, </span>{{name}}!</h3>
</div>

编辑:您也可以使用JQuery:这是一个fiddle

如果你不想使用Angular,这是有效的:

  function writeToElement(id, value){
    var target= document.getElementById("id");
    if (target) {
        target.innerHTML = value;
        return target;
    } else {
        return false;
    }
  } 

然后可以将onClick设置为writeToElement(someId, this.value),其中someId是要更改的元素的id。