gpt4 book ai didi

javascript - 单一函数捕获不同输入字段的不同值

转载 作者:行者123 更新时间:2023-11-28 13:07:24 27 4
gpt4 key购买 nike

对于下面的代码,我必须使用 4 个函数来显示 4 个输入字段中的值。

<!DOCTYPE html>
<html>
<body>

Name: <input type="text" id="name1" value="" onBlur="myFunction1()"><br>
Age: <input type="number" id="age1" value="" onBlur="myFunction2()"><br>
Job: <input type="text" id="job1" value="" onBlur="myFunction3()"> <br>
Tel: <input type="text" id="tel1" value="" onBlur="myFunction4()"> <br>

<p>Type then click outside to display the value of the input field.</p>

Your input:
<p id="demo"></p>

<script>
function myFunction1() {
var x = document.getElementById("name1").value;
document.getElementById("demo").innerHTML = x;
}
function myFunction2() {
var y = document.getElementById("age1").value;
document.getElementById("demo").innerHTML = y;
}
function myFunction3() {
var z = document.getElementById("job1").value;
document.getElementById("demo").innerHTML = z;
}
function myFunction4() {
var a = document.getElementById("tel1").value;
document.getElementById("demo").innerHTML = a;
}
</script>

</body>
</html>

有没有办法只使用 1 个函数来完成相同的工作?

最佳答案

试试这个

function myFunction1(val) {
var x = val;
document.getElementById("demo").innerHTML = x;
}
Name: <input type="text" id="name1" value="" onBlur="myFunction1(this.value)"><br>
Age: <input type="number" id="age1" value="" onBlur="myFunction1(this.value)"><br>
Job: <input type="text" id="job1" value="" onBlur="myFunction1(this.value)"> <br>
Tel: <input type="text" id="tel1" value="" onBlur="myFunction1(this.value)"> <br>

<p>Type then click outside to display the value of the input field.</p>

Your input:
<p id="demo"></p>

关于javascript - 单一函数捕获不同输入字段的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45387676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com