2015-03-25 91 views
0

我正在使用标签插件从用户获取标签输入。所使用的自动完成的标记源是通过ajax调用,该调用返回json对象,使用它我映射要向用户显示的标记的值和名称。 json对象还包含每个标记的ID,我不想向用户显示,但发送到服务器而不是标记标签/值。要做到这一点,我想我可以在自动完成中一般可用的“select”选项下使用一个函数。该功能将维护由用户选择的所有ID的数组。但是当我选择一个标签时,select函数没有被调用。我使用的代码如下:tag-it:自动完成中选择功能不起作用

$("#myTags").tagit({ 
     allowSpaces: true, 
     autocomplete: { 
      source: function (request, response) { 
       $.ajax({ 
        url: "http://localhost:5555/api/Tag", 
        dataType: "json", 
        data: { 
         strSearch: request.term 
        }, 
        success: function (data) { 
         response($.map(data, function (item) { 
          return { 
           label: item.Name, //Use rest of the data to map IDs 
           value: item.Name, 
           ID: item.ID 
          } 
         })); 
        } 
       }); 
      }, 
      minLength: 1, 
      select: function (event, ui) { 
       console.log(ui.item.label + "=" + ui.item.ID); 
      } 

     } 

    }); 

回答

0

对于我来说,使用向上/向下键和回车键时选择不起作用。用鼠标和标签工作。

我试过一些关键检测代码,如其他文章(如果键== 13)建议,但没有为我工作。

我的解决方案是把焦点事件放在我临时存储焦点的最后一个对象的地方。然后,当用户点击输入键或用鼠标点击时,我检查输入的标签是否与最后一个焦点标签相同。这与标签被“选中”的效果相同:

// Variable used to store temporarily the focused label from 
// the autocomplete list. 
var focusedTag = null; 

$('#tags-list').tagit({ 

    fieldName: 'tags', 

    autocomplete: { 

     source: function (request, response) { /* Load your list... */ }, 

     // Stored the tag that received focus temporarily, to solve 
     // enter key problem. 
     focus: function(event, ui) { 
      focusedTag = ui.item; 
     }, 

     delay: 100, 
     minLength: 3 
    }, 

    afterTagAdded: function (event, ui) { 

     if (focusedTag !== null && 
       focusedTag.label === ui.tagLabel) { 
      // Same as if it was selected... 
     } 

     focusedTag = null; 

    }, 

    allowSpaces: true 
}); 

干杯。

相关问题