2017-04-21 190 views
2

我的.onclick函數沒有執行我的腳本文件中指定的功能。這裏是我的代碼:.onclick按鈕不能執行功能

JAVASCRIPT:

var quotes = [ 
    ["「If you are distressed by anything external, the pain is not due to the thing itself, but to your estimate of it; and this you have the power to revoke at any moment.」", "Marcus Aurelius"],["「The average man is a conformist, accepting miseries and disasters with the stoicism of a cow standing in the rain.」", "Colin Wilson"], 
    ["「Never let the future disturb you. You will meet it, if you have to, with the same weapons of reason which today arm you against the present.」", "Marcus Aurelius"], 
    ["「Warriors should suffer their pain silently.」","Erin Hunter"], 
    ["「Complaining does not work as a strategy. We all have finite time and energy. Any time we spend whining is unlikely to help us achieve our goals. And it won't make us happier.」", "Randy Pausch"], 
    ["「It is the power of the mind to be unconquerable.」", "Seneca"], 
    ["「How do you defeat terrorism? Don’t be terrorized.」", "Salman Rushdie"], 
    ["「It is not the man who has too little that is poor, but the one who hankers after more.」", "Seneca"], 
    ["「What really frightens and dismays us is not external events themselves, but the way in which we think about them. It is not things that disturb us, but our interpretation of their significance.」", "Epictetus"], 
    ["「For death remembered should be like a mirror, who tells us life’s but breath, to trust it error.」", "Shakespeare"], 
    ["「No one saves us but ourselves. No one can and no one may. We ourselves must walk the path.」", "Buddha"], 
    ["「You only lose what you cling to.」", "Buddha"], 
    ["「Man suffers only because he takes seriously what the gods made for fun.」", "Alan W. Watts"], 
    ["「If there is any religion that could respond to the needs of modern science, it would be Buddhism.」", "Albert Einstein"], 
    ["「We are not going in circles, we are going upwards. The path is a spiral; we have already climbed many steps.」", "Hermann Hesse"], 
    ["「Treat every moment as your last. It is not preparation for something else.」", "Shunryu Suzuki"], 
    ["「Better than a thousand hollow words is one word that brings peace.」", "Buddha"], 
    ["「Life is painful. It has thorns, like the stem of a rose. Culture and art are the roses that bloom on the stem. The flower is yourself, your humanity. Art is the liberation of the humanity inside yourself.」", "Daisaku Ikeda"], 
    ["「Learning to let go should be learned before learning to get. Life should be touched, not strangled. You’ve got to relax, let it happen at times, and at others move forward with it.」", "Ray Bradbury"] 
]; 


var randomInt = Math.floor((Math.random() * quotes.length) + 1); 

// Generate random number 
// Get number's position from array 
var aQuote = function() { 
    return quotes[randomInt][0] + ""; 
}; 

var aQuoteAuthor = function() { 
    return quotes[randomInt][1] + ""; 
}; 


// Change textblock into quote + author 
// Display quote on page 
// Display author on page 

function changeButton() { 
    document.getElementById('quote').innerHTML = aQuote(); 
    document.getElementById('quoteAuthor').innerHTML = aQuoteAuthor(); 
}; 

// Register button press 
document.getElementById('aButton').onclick = changeButton(); 

這是我的html:

<div class="container"> 
    <div class="row"> 
     <div class="u-full-width"> 
     <div class="quotediv"> 
      <h5 id="quote" class="text-primary-color">「Imagine smiling after a slap in the face. Then think of doing it twenty-four hours a day.」</h5> 
      <p id="quoteAuthor" class="light-primary-color">Markus Zusak<p> 
      <button id="aButton" type="button button-primary" class="primary-text-color"> NEW QUOTE</button> 
     </div> 
     </div> 
    </div> 
    </div> 

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

第一個奇怪的是,該功能changeButton()獲取在頁面加載時自動調用在功能呼叫。因此,在每個頁面加載時都會生成並顯示一個新報價。第二個奇怪的是,按鈕本身不會生成並通過函數changeButton()更改引號。

任何人都可以指向正確的方向嗎?

P.S.我是一個編碼新手。這是我的第一個問題。我試圖按照指導方針的特異性,但如果您對我的問題表述有任何提示或意見,請告訴我! :)

+0

是誰喊'changeButton'功能 – brk

+1

如何事件偵聽器連接到元素'的document.getElementById( 'A按鈕')的addEventListener( '點擊',changeButton());' – snkv

+0

試試這個文件' .getElementById('#id')。on('click',changebutton());' – MUT

回答

1

問題是,您正在執行該函數並將返回值分配給onclick。

document.getElementById('aButton').onclick = changeButton(); 

你應該分配功能本身的onclick像這樣(注意它沒有「()」結尾)

document.getElementById('aButton').onclick = changeButton; 

更妙的是使用addEventListener像這樣

document.getElementById('aButton').addEventListener('click', changeButton); 
1

可以調用使用

document.getElementById('aButton').addEventListener("click", changeButton); 
onClick監聽器

使用:

document.getElementById('aButton').onclick = changeButton(); 

你只需指定函數的返回值,而不是功能分配給click事件!這條線:

document.getElementById('aButton').onclick = changeButton; 

其實分配的功能click事件(注意,沒有括號所以它不被執行,它的分配作爲變量)。

function changeButton() { 
 
\t alert("Hello") 
 
} 
 

 
document.getElementById('aButton').addEventListener("click", changeButton);
<button id="aButton">Click Me</button>

1

嘗試做這樣的:

的document.getElementById( 'A按鈕')的onclick = changeButton

什麼你做的是結合事件同時執行它。

document.getElementById('aButton').onclick = changeButton 
 

 
function changeButton() { 
 
console.log("yes"); 
 
}
<button id="aButton"> 
 
Button 
 
</button>

-2

移動你的腳本頭部分也將正常工作。

<!DOCTYPE html> 
<html> 
<head> 

<script> 
var quotes = [ 
    ["「If you are distressed by anything external, the pain is not due to the thing itself, but to your estimate of it; and this you have the power to revoke at any moment.」", "Marcus Aurelius"],["「The average man is a conformist, accepting miseries and disasters with the stoicism of a cow standing in the rain.」", "Colin Wilson"], 
    ["「Never let the future disturb you. You will meet it, if you have to, with the same weapons of reason which today arm you against the present.」", "Marcus Aurelius"], 
    ["「Warriors should suffer their pain silently.」","Erin Hunter"], 
    ["「Complaining does not work as a strategy. We all have finite time and energy. Any time we spend whining is unlikely to help us achieve our goals. And it won't make us happier.」", "Randy Pausch"], 
    ["「It is the power of the mind to be unconquerable.」", "Seneca"], 
    ["「How do you defeat terrorism? Don’t be terrorized.」", "Salman Rushdie"], 
    ["「It is not the man who has too little that is poor, but the one who hankers after more.」", "Seneca"], 
    ["「What really frightens and dismays us is not external events themselves, but the way in which we think about them. It is not things that disturb us, but our interpretation of their significance.」", "Epictetus"], 
    ["「For death remembered should be like a mirror, who tells us life’s but breath, to trust it error.」", "Shakespeare"], 
    ["「No one saves us but ourselves. No one can and no one may. We ourselves must walk the path.」", "Buddha"], 
    ["「You only lose what you cling to.」", "Buddha"], 
    ["「Man suffers only because he takes seriously what the gods made for fun.」", "Alan W. Watts"], 
    ["「If there is any religion that could respond to the needs of modern science, it would be Buddhism.」", "Albert Einstein"], 
    ["「We are not going in circles, we are going upwards. The path is a spiral; we have already climbed many steps.」", "Hermann Hesse"], 
    ["「Treat every moment as your last. It is not preparation for something else.」", "Shunryu Suzuki"], 
    ["「Better than a thousand hollow words is one word that brings peace.」", "Buddha"], 
    ["「Life is painful. It has thorns, like the stem of a rose. Culture and art are the roses that bloom on the stem. The flower is yourself, your humanity. Art is the liberation of the humanity inside yourself.」", "Daisaku Ikeda"], 
    ["「Learning to let go should be learned before learning to get. Life should be touched, not strangled. You’ve got to relax, let it happen at times, and at others move forward with it.」", "Ray Bradbury"] 
]; 


var randomInt = Math.floor((Math.random() * quotes.length) + 1); 

// Generate random number 
// Get number's position from array 
var aQuote = function() { 
    return quotes[randomInt][0] + ""; 
}; 

var aQuoteAuthor = function() { 
    return quotes[randomInt][1] + ""; 
}; 


// Change textblock into quote + author 
// Display quote on page 
// Display author on page 

function changeButton() { 
    alert(); 
    document.getElementById('quote').innerHTML = aQuote(); 
    document.getElementById('quoteAuthor').innerHTML = aQuoteAuthor(); 
}; 

</script> 
</head> 
<body> 

    <div class="container"> 
    <div class="row"> 
     <div class="u-full-width"> 
     <div class="quotediv"> 
      <h5 id="quote" class="text-primary-color">「Imagine smiling after a slap in the face. Then think of doing it twenty-four hours a day.」</h5> 
      <p id="quoteAuthor" class="light-primary-color">Markus Zusak<p> 
      <button id="aButton" type="button button-primary" class="primary-text-color"> NEW QUOTE</button> 
     </div> 
     </div> 
    </div> 
    </div> 

</body> 
</html>