在输入中获取关键字并使用jquery将它们存储在数组中

时间:2011-08-16 06:20:59

标签: jquery

我想知道如何在数组中存储这样的查询:"hello again world"

关键字将位于id = status的输入字段中,并且必须按“”拆分。另外,如何将此数组中的某些单词和字符与数组stopwords中的单词/字符匹配

3 个答案:

答案 0 :(得分:1)

//split the words by space
var keywds = $("#status").val().split(" ");
$.each(keywds,function(i,val){
   //check if its an empty string 
   if($.trim(val) == ""){
      keywds.splice(i);
   }//Check if it's in stopwords
   else if($.inArray(val,stopwords)>= 0)       
   {
      keywds.splice(i);
   }
});

http://jsfiddle.net/pfQnt/

答案 1 :(得分:0)

// get value and split the string
var keywords = $('#status').val().split(' ');
// get all keywords who are not in the array stopwords
var result = [];
for (var index in keywords) {
    if ($.inArray(keywords[index], stopwords) == -1) {
        result.push(keywords[index]);
    }
}

答案 2 :(得分:0)

您可以使用getElementById方法和元素的value属性获取输入值:

var keywords = document.getElementById('status').value;

完成后,您可以使用split方法用空格分隔:

keywords = keywords.split(' ');

你可以随时待命,保留关键字:

var stopwords = [];

最后,在插入之前,您需要检查每个新关键字:

var addUnique = function (keyword) {
        var i = stopwords.length;
        while (i) {
            i -= 1;
            if (keyword === stopwords[i]) {
                return;
            }
        }
        stopwords[stopwords.length] = keyword;
    },
    addMany = function (keywords) {
        var i = keywords.length;
        while (i) {
            i -= 1;
            addUnique(keywords[i]);
        }
    };

最终的脚本看起来像这样:

var keyword_form = document.getElementById('yourForm'),
    keyword_input = document.getElementById('status'),
    stopwords = [],
    addUnique = function (keyword) {
        var i = stopwords.length;
        while (i) {
            i -= 1;
            if (keyword === stopwords[i]) {
                return;
            }
        }
        stopwords[stopwords.length] = keyword;
    },
    addMany = function (keywords) {
        var i = keywords.length;
        while (i) {
            i -= 1;
            addUnique(keywords[i]);
        }
    };

keyword_form.onsubmit = function () {
    var keywords = keyword_input.value.split(' ');
    addMany(keywords);
};