2016-11-26 69 views
2

下面的代碼中的onclick未正確觸發警報。Onclick警告字符串

這裏是我的代碼:

function alert_phrase(id){ 
 
    var value = document.getElementById(id).value; 
 
    alert(value); 
 
}
<div id="exp" style="background-color: white;"> 
 
    <p id="content-exp" style="color: red;">HELLO WORLD!</p> 
 
    <input name="phrase" Placheholder="Enter text here" id="phrase" /> 
 
    <button onclick='alert_phrase(phrase)'>Alert this sentence</button> 
 
</div>

回答

3

嘗試......

<button onclick='alert_phrase("phrase")'>Alert this sentence</button> 

注:傳遞id作爲一個字符串alert_phrase。

段:

function alert_phrase(id){ 
 
    var value = document.getElementById(id).value; 
 
    alert(value); 
 
}
<div id="exp" style="background-color: white;"> 
 
    <p id="content-exp" style="color: red;">HELLO WORLD!</p> 
 
    <input name="phrase" Placheholder="Enter text here" id="phrase" /> 
 
    <button onclick='alert_phrase("phrase")'>Alert this sentence</button> 
 
</div>

+0

謝謝!它的工作@rfornal – willy

+0

很高興我可以協助。當我自己想念這些東西時,我發現它很粗糙......比我想要的更頻繁。 – rfornal

6

你忘了你的參數報價。希望這有助於

function alert_phrase(id){ 
 
     var value = document.getElementById(id).value; 
 
     alert(value); 
 
}
<div id="exp" style="background-color: white;"> 
 
<p id="content-exp" style="color: red;">HELLO WORLD!</p> 
 
<input name="phrase" Placheholder="Enter text here" id="phrase" /> 
 
<button onclick='alert_phrase("phrase")'>Alert this sentence</button>