使用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; 
    });
 });