我有一个h2元素,里面有样式化的内容(css),也有一个span元素,称为Highlight。我想用单击提交按钮上的文本输入来更新它。
我得到的结果(单击)是清除原始文本,然后再次刷新到跨度中,因此仍显示“ John Smith”。
//index.html
<span id="highlight">John Smith</span>
<form action="" class="form-inline">
<input id="name" type="text" placeholder="Enter name" size="35">
<input type="submit" value="Submit" class="button-btn">
</form>
//app.js
$(function(){
let name = $('#name').val();
$('.button-btn').click(function(){
$('#highlight').text(name);
});
});
当我认为我做对时,它令人沮丧,但显然并非如此。预先感谢您的解决方案。
最佳答案
原因是您要在页面加载时获取输入元素的值,并且该值为空。您应该从click事件处理程序函数内部的输入中获取值:
$(function(){
console.log($('#name').val() === ""); //true
$('.button-btn').click(function(e){
let name = $('#name').val();
$('#highlight').text(name);
e.preventDefault(); // prevented the submission of the form for demo
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="highlight">John Smith</span>
<form action="" class="form-inline">
<input id="name" type="text" placeholder="Enter name" size="35">
<input type="submit" value="Submit" class="button-btn">
</form>
关于javascript - 使用jQuery使用表单输入数据更新span元素,但不更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60594287/