我有一个脚本可以检查输入字段是否包含某个条件。
如果条件为真,则会在输入字段下提示带有消息的div。
效果很好,但如何在脚本中添加更多城市?
如果我执行OR
,例如:('Amsterdam' || 'London')
,则该脚本无法正常工作。
有人可以帮我吗?
输入字段
<input type="text" name="city" id="address" onblur="check()" value="">
的Javascript
function check() {
var name = document.getElementById('address').value;
if (name.indexOf('Amsterdam') > -1) {
$(".message").html("You get a beer!");
return false;
}
}
<div class = "message"></div>
答案 0 :(得分:0)
试试这个:
if (name.indexOf('Amsterdam') > -1 || name.indexOf('London') > -1) {
// your code
}
答案 1 :(得分:0)
你可以使用else if。这样,您可以针对不同的标准使用不同的消息。请参阅下文。
语法
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
试试这个:
if (name.indexOf('Amsterdam') > -1) {
$(".message").html("You get a beer!");
} else if(name.indexOf('London') > -1) {
$(".message").html("Other message!");
} else {
$(".message").html("Something else!");
}
return false;
如果您想检查多个标准并且只显示一条消息,则可以使用|| (或)
if (name.indexOf('Amsterdam') > -1 || name.indexOf('London') > -1) {
$(".message").html("You get a beer!");
}
答案 2 :(得分:0)
如果您不太关心性能,可以使用正则表达式,但它们被认为比indexOf()
$('button').on('click', function() {
var name = document.getElementById('address').value;
if ((/^(Amsterdam|London|Texas|Delhi|Tokyo)$/i).test(name)) {
$(".message").html("You get a beer!");
return false;
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="city" id="address" value="">
<button>
Submit
</button>
<div class="message"></div>
&#13;