如何使用Javascript基于HTML中的输入文本字段更改文本元素? [英] How to change text element based on input text field in HTML using Javascript?

查看:87
本文介绍了如何使用Javascript基于HTML中的输入文本字段更改文本元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码副本: https://jsfiddle.net/5zLyyv94/

Here's a copy of my code at: https://jsfiddle.net/5zLyyv94/

<h1 class="login-heading">
<a href="./index.html" class="lnk2">Join</a> us, 
<span id="initname">Luke</span>.</h1>
<form method="post">
<input type="text" name="first name" placeholder="First Name" required="required" class="input-txt" />
</form>

基本上,我正在尝试将名称从Luke更改为字段文本中的任何人类型对于名字。

Basicially, i'm trying to change the name from Luke to whatever the person types into the field text for first name.

所以说,他们输入他们的名字作为杰森

so say, they type in their first name as "Jason"

我想要翻译文本让卢克从卢克改为杰森。

I want the span text for Luke to change from Luke to Jason.

提前致谢!

推荐答案

这应该让你开始(必须在字段外点击才能进行更新):

This should get you started (must click outside the field for update to happen):

$('input[name=first_name]').blur(function(){
  $('#initname').text( this.value );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h1 class="login-heading">
<a href="./index.html" class="lnk2">Join</a> us, 
<span id="initname">Luke</span>.</h1>

<form method="post">
  <input type="text" name="first_name" placeholder="First Name" required="required" class="input-txt" />
</form>

您还可以使用键盘( )实时更改范围文本的方法:

You can also use the keyup() method to change the span text in real time:

$('input[name=first_name]').keyup(function(){
  $('#initname').text( this.value );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h1 class="login-heading">
<a href="./index.html" class="lnk2">Join</a> us, 
<span id="initname">Luke</span>.</h1>

<form method="post">
  <input type="text" name="first_name" placeholder="First Name" required="required" class="input-txt" />
</form>

或者,用户停止输入1.2秒(1200毫秒)后:

Or, after user stops typing for 1.2 seconds (1200 milliseconds):

pauseTime = 1200;

$('input[name=first_name]').keyup(debounce(function(event){
  $('#initname').text( this.value );
},pauseTime));

function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h1 class="login-heading">
<a href="./index.html" class="lnk2">Join</a> us, 
<span id="initname">Luke</span>.</h1>

<form method="post">
  <input type="text" name="first_name" placeholder="First Name" required="required" class="input-txt" />
</form>

参考文献:

https://remysharp.com/2010/07/21/throttling-function-calls

这篇关于如何使用Javascript基于HTML中的输入文本字段更改文本元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆