2014-01-25 38 views
4

我在標記模式下使用select2。我的項目文本是一個鏈接,例如:通過鏈接在select2標記中單擊事件

<a href='url'>tag1</a>. 

選擇2似乎是吞嚥的標籤(所選的選項)的點擊事件,所以我不能瀏覽到的鏈接。

有關如何讓鏈接工作的任何想法?

回答

10

默認情況下,Select2禁用點擊事件,並且目前您必須使用解決方法來獲得所需的結果。以下是我如何完成此任務的示例,這要歸功於以下資源。

<a href="#" class="detail-link">hello</a> 

然後你:如果你不使用。數據的返回值(「選擇2」)

首先,一類添加到您的鏈接重新實例變量這將無法正常工作聽的選擇二

var search = $("#searchBox"); 
    search.select2({ 
     placeholder: "Search...", 
     allowClear: true, 
     minimumInputLength: 3, 
     maximumSelectionSize: 1, 
     escapeMarkup: function(m) { return m; }, 
     ajax: {  blah blah blah  }, 
     formatResult: window.App.formatFunction 
    }); 


    search= search.data('select2'); 

    search.onSelect = (function(fn) { 
     return function(data, options) { 
      var target; 

      if (options != null) { 
       target = $(options.target); 
      } 

      if (target && target.hasClass('detail-link')) { 
       window.location = target.attr('href'); 
      } else { 
       return fn.apply(this, arguments); 
      } 
     } 
    })(search.onSelect); 

這個問題/答案onSelect事件/ JFiddle幫了我,但它一定要注意。數據(「選擇2」)線

編輯:忘了資源 - https://stackoverflow.com/a/15637696

+0

我實際上指的是顯示所選標籤(未在搜索結果下拉列表)。但上面的作品通過使用selectChoice而不是onSelect。例如。 「search.selectChoice =(func ...」 – bobdev

4

我用select2-selecting event

var $q = $('#select2input'); 
$q.select2({ 
    // your settings 
}); 

$q.on('select2-selecting', function(e){ 
    window.location = e.choice.url; 
}); 

我的AJAX的有效載荷是這樣的:

{ 
    "items":[ 
     { 
      "id": "1", 
      "text": "Foo", 
      "url": "/foo" 
     }, 
     { 
      "id": "8", 
      "text": "Bar", 
      "url": "/bar" 
     } 
    ] 
} 
+2

在版本4+中,select事件是'select2:choose'。[This SO answer](http://stackoverflow.com/a/18615267/997596) – Fisu