使用JQuery
自动填充功能,我有一个功能可以生成用户在框中输入的Array
个朋友。
此数组称为selected_Id
。但是,我们的项目已经扩展,并与“朋友”选择(<--the one that produces the selected_Id array)
我们想添加'敌人'功能。
可以重写那段代码来生成2个独立的数组吗?如果我将它们分开,它将调用getfriends函数两次(the getfriends function produces an array of available friends that loads into the jQuery ui that the user gets to choose from)
。
这就是我所拥有的:
$(function() {
var available = new Array();
available = getFriends();
available = my_friends
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
available, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
//replaced value with label to continue showing the names selected
terms.push( ui.item.label);
//ui.item.valuethis is where my
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
$( "button" ).button();
$( "button" ).click(function() {
var selected_Text = $( "#tags" ).val();
var selected_Friends = selected_Text.split(",");
//friend name put in the autocomplete box
var friend_Name = "";
//selected id of the person in the array
var testCount = 0;
//i < j --> run through interation once
for(var i = 0, j=selected_Friends.length; i<j; i++ )
{
friend_Name = selected_Friends[i];
while (friend_Name[0] == " "){
friend_Name = friend_Name.substring(1,friend_Name.length);
}
for (var k = 0, l = my_friends.length; k<l; k++)
{
if (friend_Name == my_friends[k]["label"])
{
selected_Id.push(my_friends[k]["value"])
testCount++;
} else {
}
}
}
return false;
});
});
答案 0 :(得分:3)
您可以返回数组对象:
function someFunction() {
return {
enemies: [1, 2, 3],
friends: [4, 5, 6]
};
}
console.log(someFunction().enemies) //The array of [1,2,3]
答案 1 :(得分:0)
通过阅读你的问题我说...你可以通过将这两个数组封装在一个对象中并返回该对象来从函数返回两个数组。
function get2arrays() {
var firstArray = new Array();
var secondArray = new Array();
......
return { First: firstArray, Second: secondArray };
}