gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'value' of null Error for while changing value of INNER HTML

转载 作者:行者123 更新时间:2023-11-27 22:54:51 25 4
gpt4 key购买 nike

下面是我的 JavaScript 代码。我想显示名字+姓氏而不是“欢迎用户”(标题文本)。我在控制台中收到错误消息“Uncaught TypeError: Cannot read property 'value' of null”

<!DOCTYPE html>
<html>
<head>
<title>This is Title</title>
<script type="text/javascript">
function substitute(){
var lastname=document.getElementById('lastname_id').value;
var firstname=document.getElementById('firstname_id').value;
console.log(lastname);
console.log(firstname);
if(lastname.length==0 || firstname.length==0){
alert('Please enter values');
return;
}
var myTitle=document.getElementById('user').value;
console.log(myTitle);
var myvalue = firstname+lastname;
console.log(myvalue);
myTitle.innerHTML = myvalue;
}
</script>
</head>
<body>
<form>
<h1 id="title">Welcome User</h1>
First name:<br>
<input type="text" name="firstname" id="firstname_id">
<br>
Last name:<br>
<input type="text" name="lastname" id="lastname_id">
<input type="submit" value="Submit" id="submit_id" onclick="substitute()">
</form>

</body>
</html>

最佳答案

您正在访问带有 id=user 的元素,但没有带有 id=user 的元素

document.getElementById('user').value;

您需要将上面的行更改为

document.getElementById('title');

因为你有一个元素h1,id为title

关于javascript - 未捕获的类型错误 : Cannot read property 'value' of null Error for while changing value of INNER HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716280/

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