如何使用 Javascript 根据 HTML 中的输入文本字段更改文本元素?

2022-01-17 00:00:00 jquery javascript html html5-canvas

这是我的代码副本: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.

也就是说,他们输入的名字是Jason"

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

我希望 Luke 的 span 文本从 Luke 更改为 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>

也可以使用keyup()方法实时改变span文本:

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-函数调用

相关文章