2015-11-09 44 views
1

我無法確定什麼是'null'。我認爲它可能是表單按鈕,因爲表單和按鈕ID不一樣...控制檯說問題出在'button1.onclick = createParagraph;'上線。請幫忙。表單按鈕'無法設置屬性'onclick'null'

下面是我的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> 
+0

是randomMad.js在哪裏包含上面的腳本? – AtheistP3ace

+0

是的,這是對腳本文件的引用。 – maxwelldem

回答

1

你缺少一些你行; ..

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

類在這兩行的末尾添加一個;

UPDATE

錯誤可能會導致因爲你試圖在DOM完成加載之前訪問的元素。因此,要解決這個問題,你可以移動

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

<body>結束。

+2

我可能在這裏是錯的,但JavaScript仍然可以用分號忽略,所以我不認爲這是問題。 *編輯*無所謂,當使用'''''''''''或'()'時是必需的。 –

+0

是的,這是正確的.. @TimLewis ..只是爲了確保它不是問題,他應該嘗試結束這些行用';'。我已經更新了我的asnwer .. – Lal