jQuery 将逗号分隔的输入框值拆分为jquery中的数组,并循环遍历它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11757671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:55:13  来源:igfitidea点击:

Split comma-separated input box values into array in jquery, and loop through it

jquery

提问by stats101

I have a hidden input box from which I'm retrieving the comma-separated text value (e.g. 'apple,banana,jam') using:

我有一个隐藏的输入框,我从中检索逗号分隔的文本值(例如'apple,banana,jam'):

var searchTerms = $("#searchKeywords").val();

I want to split the values up into an array, and then loop through the array.

我想将值拆分成一个数组,然后遍历该数组。

回答by Jitendra Pancholi

var array = $('#searchKeywords').val().split(",");

then

然后

$.each(array,function(i){
   alert(array[i]);
});

OR

或者

for (i=0;i<array.length;i++){
     alert(array[i]);
}

回答by Antguider

var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

回答by Saeed

use js split() method to create an array

使用js split()方法创建数组

var keywords = $('#searchKeywords').val().split(",");

then loop through the array using jQuery.each() function. as the documentationsays:

然后使用 jQuery.each() 函数遍历数组。正如文档所说:

In the case of an array, the callback is passed an array index and a corresponding array value each time

在数组的情况下,回调每次都会传递一个数组索引和一个对应的数组值

$.each(keywords, function(i, keyword){
   console.log(keyword);
});