gpt4 book ai didi

javascript - 表单按钮 'Cannot set property ' onclick'of null'

转载 作者:行者123 更新时间:2023-11-27 23:41:37 24 4
gpt4 key购买 nike

我无法确定什么是“null”。我认为这可能是表单按钮,因为表单和按钮 id 不一样...控制台说问题出在“button1.onclick = createParagraph;”上线。请帮忙。

下面是我的 JavaScript

//global variables for user input
var noun1;
var noun2;
var adjective1;
var adjective2;
var verb1;
var verb2;
var paragraph1 = "hello, did this work?"
var button1 = document.getElementById("pushMe")

//to retrieve values from user input, and write to global variables
function handleSubmit(form) {
noun1 = form.querySelector('input[name=noun1]').value;
noun2 = form.querySelector('input[name=noun2]').value;
adjective1 = form.querySelector('input[name=adjective1]').value;
adjective2 = form.querySelector('input[name=adjective2]').value;
verb1 = form.querySelector('input[name=verb1]').value;
verb2 = form.querySelector('input[name=verb2]').value;

return false;
}

//to write paragraph to the DOM
function createParagraph () {
var element = document.createElement("p");
var content = document.createTextNode("paragraph1");
var location = document.getElementById("placeholder");
element.appendChild(content);
document.body.insertBefore(element,location);
}

//run it all!
button1.onclick = createParagraph;

下面是 HTML

    <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='https://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="stylesheets/madlib.css">
<script src="randomMad.js"></script>
<title>Mad Libs!</title>
</head>
<header>

</header>
<body>
<form onsubmit="return handleSubmit(this)" id="form1">
<h1>Choose your words!</h1>
<fieldset>
<label>First Noun: <input type="text" name="noun1" ></label><br>
<label>Second Noun: <input type="text" name="noun2"></label><br>
<label>First Adjective: <input type="text" name="adjective1"></label><br>
<label>Second Adjective: <input type="text" name="adjective2"></label><br>
<label>First Verb: <input type="text" name="verb1"></label><br>
<label>Second Verb: <input type="text" name="verb2"></label><br>
</fieldset>
<button type="submit" id="pushMe">Create Mad Lib</button>
</form>
<div id="placeholder">

</div>
</body>

最佳答案

您缺少;在你的一些台词中..

查看

var paragraph1 = "hello, did this work?"
var button1 = document.getElementById("pushMe")

请添加;在那两行的末尾。

更新

导致该错误的原因可能是您尝试在 DOM 完成加载之前访问该元素。因此,要解决该问题,您只需移动

<script src="randomMad.js"></script>

<body>结尾.

关于javascript - 表单按钮 'Cannot set property ' onclick'of null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612268/

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