2017-05-03 79 views
0

我正在使用Select2 v4.0.3我使用ajax填充元素。選擇項目前重定向選擇2

$("#el").select2({   
    multiple: true 
    maximumSelectionSize: 1, 

    ajax: { 
     url: url, 
     data: function (params) { 
      return { 
       name: params.term 
      }; 
     }, 
     processResults: function (data) {     
      return { 
       results: $.map(data.results, function(obj) { 
        return {id: obj.id, text: obj.name, key: obj.key};       
        } 
       }) 
      }; 
     } 
    }   
}); 

我想重定向選擇結果之前的客戶端。問題是我需要從點擊結果key屬性。爲了更好地理解我想要做的事情,我在這裏粘貼一個選擇完成後的代碼片段。

$("#el").on("select2:select", function(e) { 
    var selected = $(this).select2('data')[0]; 
    location.href = base_url + '?key=' + selected.key; 
}); 

回答

0

您可以使用event.params.args.data.id從單擊的結果中獲取關鍵屬性。所以,你的代碼可能會工作像:

$("#el").on("select2:select", function(e) { 
    var selected = event.params.args.data.id; 
    location.href = base_url + '?key=' + selected; 
}); 

我稍微修改了官方Github上存儲庫例子來說明我的觀點。

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> 
 
    <meta content="utf-8" http-equiv="encoding"> 
 
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" /> 
 
</head> 
 

 
<body> 
 
    <select class="js-data-example-ajax" style="width: 100%"> 
 
     <option value="3620194" selected="selected">select2/select2</option> 
 
    </select> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> 
 
    <script> 
 
     $(".js-data-example-ajax").select2({ 
 
      ajax: { 
 
       url: "https://api.github.com/search/repositories", 
 
       dataType: 'json', 
 
       delay: 250, 
 
       data: function(params) { 
 
        return { 
 
         q: params.term, // search term 
 
         page: params.page 
 
        }; 
 
       }, 
 
       processResults: function(data, params) { 
 
        // parse the results into the format expected by Select2 
 
        // since we are using custom formatting functions we do not need to 
 
        // alter the remote JSON data, except to indicate that infinite 
 
        // scrolling can be used 
 
        params.page = params.page || 1; 
 

 
        return { 
 
         results: $.map(data.items, function(ghrepo) { 
 
          return { 
 
           text: ghrepo.archive_url, 
 
           id: ghrepo.archive_url 
 
          } 
 
         }) 
 
        } 
 

 
       }, 
 
       cache: true 
 
      }, 
 
      escapeMarkup: function(markup) { 
 
       return markup; 
 
      }, 
 
      minimumInputLength: 1 
 
     }).on('select2:selecting', function(event, params) { 
 
      event.preventDefault(); 
 
      repoId = event.params.args.data.id; 
 
      console.log(repoId); 
 
     }); 
 
    </script> 
 
</body> 
 

 
</html>