猿问

为什么正则表达式匹配输入但警报仍然发生?

您还必须切换 btn-primary 然后它会更改背景颜色


    jQuery(function ($) {

        $('#swapFire').on('click', function () {

            var $el = $(this),

                textNode = this.lastChild;

            $el.find('span').toggleClass('glyphicon-fire glyphicon-tint');

            $el.toggleClass('btn-primary btn-success');

            $el.toggleClass('showFire');


        });

    });

.btn {

  margin: 20px;

}

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>



<button id="swapFire" class="btn btn-primary showFire">

    <span class="glyphicon glyphicon-fire"></span> Gimme Fire

</button>


精慕HU
浏览 99回答 1
1回答

手掌心

您的代码对所有输入返回 invalid 的原因是因为您实际上并未针对输入的输入进行测试,而是针对空字符串进行测试''。.innerHTML将返回一个空字符串,因为标签的开头和结尾之间没有 HTML input。要获取控件的值,请尝试使用类似的方法,var tel = document.getElementById("tel").value; 这将返回实际的用户输入。所以你的代码应该是这样的:function validate() {&nbsp; var tel = document.getElementById("tel").value;&nbsp; var email = document.getElementById("email").value;&nbsp; var pcode = document.getElementById("pcode").value;&nbsp; var tvalid = /^(\d{3}-\d{3}-\d{3}-\d{4})$/;&nbsp; if (!tvalid.test(tel)) {&nbsp; &nbsp; alert("Not a valid Phone Number");&nbsp; }&nbsp; if (!(/@gmail\.com$/.test(email)) && !(/@hotmail\.com$/.test(email)) && !(/@outlook\.com$/.test(email))) {&nbsp; &nbsp; alert("Not a valid email");&nbsp; }&nbsp; var pvalid = /^([A-Z][A-Z]\d{2}-[a-z]\d[A-Z]\d)$/;&nbsp; if (!pvalid.test(pcode)) {&nbsp; &nbsp; alert("Not a valid postal code.");&nbsp; }}<label for="tel">Phone Number</label><input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br><input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br><label for="email">Email Address</label><input type="email" id="email" name="email" placeholder="xxx@(gmail/hotmail/outlook).com" required><br><label for="pcode">Postal Code</label><input type="text" id="pcode" name="pcode" placeholder="AA11-c1V2"><br><button type="button" id="submit" onclick="validate()">Validate</button>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答