如何在JavaScript中查找文本框中的单词 [英] How to look for a word in textbox in JavaScript

查看:84
本文介绍了如何在JavaScript中查找文本框中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为Google Now制作了一个类似网站的网站,我想知道如何让JavaScript查找文本框中的某个单词。例如,如果有人在文本框中键入显示我的天气,JavaScript世界将查看关键字天气,它会向我显示天气。这里是我的代码:

JavaScript:

  function showAlert() {

var txtCtrl = document.getElementById(textbox1);

var txtVal = txtCtrl.value;

if(txtVal ==''){
alert('请填写文本框,对于命令列表,在文本框中输入帮助。
} else if(txtVal =='Start'{
alert('Hello。What do you like me to do?');
} else if(txtVal ==='Weather' ){
window.location =https://www.google.com/#q=weather;
} else if(txtVal ==='Time'){
alert( '根据你的计算机的当前时间是'+ formatTime(new Date()));
} else if(txtVal ==='Help'){
window.location =help / index。 html;
} else if(txtVal ==='Donate'){
window.location =donate / index.html;
} else if(txtVal ==='WWW 。'||){

} else {
alert('抱歉,我没有调整过这个命令,对于一个命令列表,在文本框中输入Help)。 ;
}
}
//以24小时的格式显示时间
函数showTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
return [h,m] .join(':')
}
// Show time in 12小时的表格at
var formatTime =(function(){
function addZero(num){
return(num> = 0&& num< 10)? 0+ num:num +;
}

返回函数(dt){
var formatted ='';

if(dt){
var hours24 = dt.getHours();
var hours =((hours24 + 11)%12)+ 1;
formatted = [formatted,[addZero(hours),addZero(dt.getMinutes())]。join(:),hours24> 11? PM:AM]。join();
}
返回格式化;
}
})();

和HTML:

 <!doctype html> 
< html>
< head>
< title>随机项目< / title>
< / head>
< body>
< div class =container>
< img class =logosrc =logo.pngwidth =450height =110alt =随机项目>
< input type =textname =textbox1value =spellcheck =falsedir =ltrplaceholder =Type hereid =textbox1>< br>
< button id =button1name =button1aria-label =帮我onClick =showAlert();>
< span id =button1_text>帮助我< / span>
< / button>
< div class =separator>< / div>
< span class =information>& copy;版权DemDevs 2013.保留所有权利。由Omar Latreche制作< br>< a href =donate / index.html>立即捐赠< / a>< / span>
< div class =tip>
< span class =tip>提示:< / span>< span class =tip_text>这些命令不区分大小写< / span>
< / div>
< / div>
< div class =>< / div>
< / body>
< / html>

任何帮助都将不胜感激。



Thanks,Omar!

解决方案

您可以检查字符串是否包含子字符串。使用 indexOf 函数,它返回给定字符串在其父字符串中的位置。试试这个:

  if(txtVal ==''){
alert('请填写文本框。有关命令列表,请在文本框中键入帮助。
} else if(txtVal.indexOf(start)!= -1){
alert('Hello。你想让我做什么?');
} else if(txtVal.indexOf(weather)!= -1){
window.location =https://www.google.com/#q=weather;
}
//等等。

如果未找到值 start ,则函数返回-1。 / p>

和。如果你有很多这样的功能,你应该把所有的功能单词放到数组中,然后避免那个太大的if / else系统。那么你应该检查该数组,如果存在相应的函数。我做了一个函数来帮助你的项目:

pre $ 函数returnWord(value,array){
if(!(value in数组)){
return array [value]();
}
else {
alert('returnWord()error:在干草堆中找不到针');


$ / code>

像这样调用它:

  var words = {
start:function(){alert('Hello。你想让我做什么?'); },
weather:function(){window.location =https://www.google.com/#q=weather; },
time:function(){alert('根据你电脑的当前时间是'+ formatTime(new Date())); },
/ *这里的所有函数* /
};

returnWord(txtVal,words);


I am making a website simular to the app Google Now and I was wondering how to make JavaScript look for a certain word in a textbox. So for example if someone was to type "Show me the weather" into the textbox the JavaScript world see the keyword weather and it would show the me the weather. Here is my code:

JavaScript:

function showAlert() {

    var txtCtrl = document.getElementById("textbox1");

    var txtVal = txtCtrl.value;

    if (txtVal == '') {
        alert('Please fill in the text box. For a list of commands type "Help" into the text box.');
    }else if (txtVal == 'Start' {
        alert('Hello. What would you like me to do?');
    }else if (txtVal === 'Weather') {
        window.location = "https://www.google.com/#q=weather";
    }else if (txtVal === 'Time') {
        alert('The current time according to your computer is' + formatTime(new Date()));
    }else if (txtVal === 'Help') {
        window.location = "help/index.html";
    }else if (txtVal === 'Donate') {
        window.location = "donate/index.html";
    }else if (txtVal === 'WWW.' ||) {

    }else{
        alert('Sorry, I do not reconise that command. For a list of commands, type "Help" into the text box.');
    }
}
//Show time in 24hour format
function showTime(){
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes(); 
  return [ h, m ].join(':')
}
//Show time in 12hour format
var formatTime = (function () {
    function addZero(num) {
        return (num >= 0 && num < 10) ? "0" + num : num + "";
    }

    return function (dt) {
        var formatted = '';

        if (dt) {
            var hours24 = dt.getHours();
            var hours = ((hours24 + 11) % 12) + 1;
            formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "PM" : "AM"].join(" ");            
        }
        return formatted;
    }
})();

And the HTML:

<!doctype html>
<html>
<head>
<title>Random Project</title>
</head>
<body>
<div class="container">
    <img class="logo" src="logo.png" width="450" height="110" alt="Random Project">
    <input type="text" name="textbox1" value="" spellcheck="false" dir="ltr" placeholder="Type here" id="textbox1"><br>
    <button id="button1" name="button1" aria-label="Help me" onClick="showAlert();">
        <span id="button1_text">Help me</span>
    </button>
    <div class="separator"></div>
    <span class="information">&copy; Copyright DemDevs 2013. All rights reserved. Made by Omar Latreche<br><a href="donate/index.html">Donate now</a></span>
    <div class="tip">
        <span class="tip">Tip: </span><span class="tip_text">The commands are NOT case sensitive</span>
    </div>
</div>
<div class=""></div>
</body>
</html>

Any help will be greatly appreciated.

Thanks, Omar!

解决方案

You can check if string contains substring. Use indexOf function, it returns position of given string in its parent string. Try this:

if (txtVal == '') {
    alert('Please fill in the text box. For a list of commands type "Help" into the text box.');
} else if (txtVal.indexOf("start") != -1) {
    alert('Hello. What would you like me to do?');
} else if (txtVal.indexOf("weather") != -1) {
    window.location = "https://www.google.com/#q=weather";
}
// and so on.

Function returns -1, if the value start is not found.

And. If you have lots and lots of those functions, you should put all the function words to array, and then avoid that too large if/else system. Then you should check that array, if corresponding function exists. I made function to help your project:

function returnWord(value, array) {
    if (!(value in array)) {
        return array[value]();
    }
    else {
        alert('returnWord() error: No needle found in haystack');
    }
}

Call it like this:

var words = {
             start: function() { alert('Hello. What would you like me to do?'); },
             weather: function() { window.location = "https://www.google.com/#q=weather"; },
             time: function() { alert('The current time according to your computer is' + formatTime(new Date())); },
             /* all the functions here */
            };

returnWord(txtVal, words);

这篇关于如何在JavaScript中查找文本框中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆