簡體   English   中英

簡單的Javascript OnClick功能無法正常工作

[英]Simple Javascript OnClick function not working

我試圖通過創建一個數學問題使用JavaScript創建一個簡單的驗證碼。 這不起作用。 對我做錯了什么的想法?

What does four + 3 equal? <br>
<input type="text" name="secquestion" id="secquestion" value="" placeholder="Type Numberic Answer Here (Ex. 9)">


 <input type="submit" value="  Send  " class="button" name="button" onclick="if (value !== "7") {alert('You must answer the security question correctly!');return false}">

問題是你的條件語句中使用的雙引號是亂搞onclick值周圍的雙引號。 用這個

<input type="submit" value=" Send " class="button" name="button" onclick="if (value !== '7') {alert('You must answer the security question correctly!');return false}">

你需要刪除雙引號,另外你需要告訴你的條件函數你感興趣的元素值。

通過使用javascripts documentGetElementById我們可以指定我們感興趣的文檔中的哪個元素。然后我們選擇value屬性以獲取用戶的輸入並在條件語句中測試它。

    What does four + 3 equal? <br>
    <input type="text" name="secquestion" id="secquestion" value="" placeholder="Type Numberic Answer Here (Ex. 9)">


     <input type="submit" value="  Send  " class="button" name="button" onclick="if(document.getElementById('secquestion').value != 7) {alert('You must answer the security question correctly!');return false}">

就個人而言,通過將此條件限制為其自己的函數來維護此代碼可能更容易:

    <html>
    What does four + 3 equal? <br>
    <input type="text" name="secquestion" id="secquestion" value="" placeholder="Type Numberic Answer Here (Ex. 9)">


    <input type="submit" value="  Send  " class="button" name="button" onclick="checkCaptcha()">

    <script type="text/javascript">
        function checkCaptcha(){
           if(document.getElementById("secquestion").value != 7){

               alert('You must answer the security question correctly!');

               return false;
           }

           return true;
         }
    </script>
    </html>

這個問題只有雙引號。

以下代碼有效。

What does four + 3 equal? <br>
<input type="text" name="secquestion" id="secquestion" value="" placeholder="Type Numberic Answer Here (Ex. 9)">


 <input type="submit" value="  Send  " class="button" name="button" onclick="if (value !== '7') {alert('You must answer the security question correctly!');return false}">

的jsfiddle

你的報價已經關閉。

onclick="if (value !== "7")....

需要onclick =“if(value!=='7')....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM