创建定义的更好方法

时间:2015-03-05 08:19:12

标签: jquery arrays dictionary

我目前有一个系统,用户点击一个单词并显示该单词的定义。我目前有一个点击功能:

                thisWord = $(this).html()

                if(thisWord == 'Every'){
                    thisDefinition = 'Each and all parts of something'
                } else if(thisWord == 'morning'){
                    thisDefinition = 'The early part of the day, beginning when the sun rises and ending about noon.'
                }  else if(thisWord == 'woke'){
                    thisDefinition = 'To come out of sleep'
                } else if(thisWord == 'up'){
                    thisDefinition = 'To come out of sleep'
                } else if(thisWord == 'feeling'){
                    thisDefinition = 'An emotion such as anger or sadness'
                } else if(thisWord == 'worried'){
                    thisDefinition = 'To feel anxious or nervous'
                } 

  $('.definition').append(thisDefinition)

我只是想知道,有没有比使用if语句更好的方法呢?我正在考虑使用一系列单词和定义,但却想不出如何设置它以及如何调用它?

2 个答案:

答案 0 :(得分:1)

您可以这样做:

var dex={
   every:'each and all..', 
   morning:'the early part...'
}

将每个单词存储在key为该单词且该单词的值为definition的对象中。

例如,您点击了每一个:

function getDefinition(){
    var word= $('your selector').text().toLowerCase();
    return dex[word];
}

同样查看here。我为你做了jsfiddle

答案 1 :(得分:1)

您可以为此创建array并将搜索字词应用为关键参数。

var defination = [];
defination['Every'] = "Each and all parts of something";
defination['morning'] = "The early part of the day, beginning when the sun rises and ending about noon.";
defination['woke'] = "To come out of sleep";
defination['up'] = "To come out of sleep";
defination['feeling'] = "Each and all parts of something";
defination['worried'] = "To feel anxious or nervous";

thisWord = $(this).html();     //thisWord = "worried"; 
alert(defination[thisWord]);

<强> Demo