Onclick提醒一个字符串

时间:2016-11-26 02:08:01

标签: javascript

以下代码中的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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:6)

您忘记了参数的引号。希望这有帮助

&#13;
&#13;
function alert_phrase(id){
         var value = document.getElementById(id).value;
         alert(value);
 }
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

试试这个......

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

注意:将id作为字符串传递给alert_phrase。

段:

&#13;
&#13;
function alert_phrase(id){
  var value = document.getElementById(id).value;
  alert(value);
}
&#13;
<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>
&#13;
&#13;
&#13;