如何验证两个可能的值?

时间:2011-11-10 07:50:49

标签: javascript javascript-events

如何获得以下功能以验证2个值。例如,将表格输入与“man”和“stevesho.com”匹配,而不仅仅是“man”。感谢。

function access()
{
    if(document.getElementById('letters').value=='man')
        location.href='http://www.google.com'
    else if(document.getElementById('letters').value=='woman')
        location.href='http://www.dynamicdrive.com'
    else if(document.getElementById('letters').value=='cat')
        location.href='http://www.youtube.com'
    else if(document.getElementById('letters').value=='dog')
        location.href='http://www.dailymotion.com'
    else alert('Access denied. Try again.')
}

3 个答案:

答案 0 :(得分:0)

function access()
{  
    var letters = document.getElementById('letters').value;  
    var goto_link = "";
    switch(letters){  
        case 'man': 
        case 'stevesho.com':
            goto_link = 'http://www.google.com';
            break;
        case 'woman':
            goto_link = 'http://www.dynamicdrive.com';
            break;
        case 'cat':
            goto_link = 'http://www.youtube.com';
            break;
        case 'dog':
            goto_link = 'http://www.dailymotion.com';
            break;
        default: 
            alert('Access denied. Try again.')
            return;
    }
    location.href = goto_link;
}

答案 1 :(得分:0)

不能是:

function access()
{
    var s = document.getElementById('letters').value;
    if(s =='man' || s = 'stevesho.com')
        location.href='http://www.google.com'
    else if(s =='woman')
        location.href='http://www.dynamicdrive.com'
    else if(s =='cat')
        location.href='http://www.youtube.com'
    else if(s =='dog')
        location.href='http://www.dailymotion.com'
    else alert('Access denied. Try again.')
}

答案 2 :(得分:0)

您在寻找OR运营商吗?见http://www.w3schools.com/js/js_comparisons.asp

var letter = document.getElementById('letters').value

if (letter == 'man' || letter == 'stevesho.com')
    location.href = 'http://www.google.com'

可能感兴趣的另一种选择;

var key = document.getElementById('letters').value

var collection = {
    "key1" : "url1",
    "key2" : "url2",
    "key3" : "url3",
    "man" : "http://www.google.com",
    "stevesho.com" : "http://www.google.com"
};

if (collection[key]) {
    var url = collection[key];
    alert(key + " = " + url); // DEBUG
    //location.href = url;
}
else {
    alert("Access denied. Try again.");
}