2016-11-26 89 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>