簡體   English   中英

檢測文本框是否不包含某些單詞

[英]Detect if a textbox does not contain certain words

我想知道如何檢測文本框是否不包含某些單詞。 例如,如果文本框不包含“誰”,“什么”,“為什么”,“何時”或“何處”,則將運行某種功能。

JavaScript:

function command() {
    var srchVar = document.getElementById("srch");
    var srch = srchVar.value;
    var t = srch;
    if (srch == '') {
        alert('Please do not leave the field empty!');
    }
    else if (srch.indexOf('time') != -1) {
        alert('The current time according to your computer is' + ShowTime(new Date()));
    }
    else if (srch.indexOf('old are you') != -1) {
        alert("I am as old as you want me to be.");
    }
    else {
        if (confirm('I am sorry but I do not understand that command. Would you like to search Google for that command?') == true) {
            window.open('https://google.co.uk/#q=' + srch, '_blank');
        }
        else { /* Nothing */ }
    }
}

HTML:

<!DOCTYPE html>
<html>
<head>
    <script src="script.js" type="text/javascript"></script>
    <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
    <div class="ui-widget">
        <input class="search-field" id="srch" onkeypress="searchKeyPress(event);" placeholder="ask me anything" spellcheck="false">
    </div>
</body>
</html>

您將需要在按下按鈕時調用該功能。 嘗試在HTML中執行以下操作:

<input class="info" onclick="contains();" type="button">

在你的JS里

function contains() {
    var srchVar = document.getElementById("srch");
    var srch = srchVar.value;

    if (
        (srch.indexOf('who')==-1) &&
        (srch.indexOf('what')==-1) &&
        (srch.indexOf('why')==-1) &&
        (srch.indexOf('when')==-1) &&
        (srch.indexOf('where')==-1)
    ) {
          alert("That is not a question");
    }
}

將來您將希望將此與您的command()函數合並。

另外, info();是什么info(); 怎么辦?

暫無
暫無

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

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