提交时如何更改文本
Posted
技术标签:
【中文标题】提交时如何更改文本【英文标题】:How do i change the text when i'm submitting 【发布时间】:2020-09-20 18:05:49 【问题描述】:提交时,我无法将“输入您的年龄”中的文本更改为“您的年龄”。有没有办法在我提交 DOB 时将“输入您的年龄”更改为“您的年龄是:X”?
function myFunction()
var dobString = document.getElementById("birth_date").value;
var calculatedValue = calculate_age(dobString);
function calculate_age(dobString)
var diff_ms = Date.now() - Date.parse(dobString);
var yearString = "";
var yearValue = Math.floor(diff_ms / 31536000000);
console.log("Years ", yearValue);
if (yearValue > 1)
yearString = " years";
else
yearString = " year";
if (yearValue > 0)
var calculatedValue = yearValue + yearString + " ";
else if (yearValue == 0)
var calculatedValue = monthValue + monthString + " ";
document.getElementById("age").innerhtml = "Your Age is : " + calculatedValue;
<form>
Birthday: <input type="date" name="bday" id="birth_date">
<br><br>
</form>
<button onclick="myFunction()">view</button><br>
<h2>Enter your age</h2>
<p id="age"></p>
【问题讨论】:
【参考方案1】:将模板更新为
<h2 id="age">Enter your age</h2>
并将脚本更新为这样
document.getElementById("age").textContent = "Your Age is : " + calculatedValue;
【讨论】:
【参考方案2】:很简单,把id="age"
放在<h2>
上
function myFunction()
var dobString = document.getElementById("birth_date").value;
var calculatedValue = calculate_age(dobString);
function calculate_age(dobString)
var diff_ms = Date.now() - Date.parse(dobString);
var yearString = "";
var yearValue = Math.floor(diff_ms / 31536000000);
console.log("Years ", yearValue);
if (yearValue > 1)
yearString = " years";
else
yearString = " year";
if (yearValue > 0)
var calculatedValue = yearValue + yearString + " ";
else if (yearValue == 0)
var calculatedValue = monthValue + monthString + " ";
document.getElementById("age").innerHTML = "Your Age is : " + calculatedValue;
<form>
Birthday: <input type="date" name="bday" id="birth_date">
<br><br>
</form>
<button onclick="myFunction()">view</button><br>
<h2 id="age">Enter your age</h2>
【讨论】:
但是段落标签的 id 是年龄。只是移动它不会解决问题【参考方案3】:您需要稍微不同地计算年龄。 也许是这样的:
function calculate_age(dobString)
var birthday = new Date(dobString), //Year, month, day.
today = new Date(),
one_year = 1000*60*60*24*365;
let yearValue = Math.floor( (today.getTime() - birthday.getTime() ) / one_year);
let yearString = 'year'
if (yearValue > 1) yearString += "s" ;
document.getElementById("age").innerHTML = `Your Age is : $yearValue $yearString`;
我创建了一个小提琴供您查看它的实际效果:
https://jsfiddle.net/cdrsfo82/
【讨论】:
以上是关于提交时如何更改文本的主要内容,如果未能解决你的问题,请参考以下文章
Swift:如何在单击提交按钮时更改 UIButton 图像