jjzjj

javascript - Bootstrap Typeahead 不显示 valueKey 以相同值开头的建议

coder 2025-01-07 原文

我正在使用 typeahead v0.11.1 来显示结果,但它没有显示以相同结果开头的结果。

我从数据库中得到的结果是这样的:

Object {
  Id: 4,
  Title: "project manager",
  Description: "project manager",
  CompanyId: 1
}
Object {
  Id: 6,
  Title: "Software Developer",
  Description: "Software Developer",
  CompanyId: 1
}
Object {
  Id: 7,
  Title: ".NET Developer",
  Description: ".NET Developer",
  CompanyId: 1
}
Object {
  Id: 10,
  Title: "Android Developer",
  Description: "Android Developer",
  CompanyId: 1
}
Object {
  Id: 11,
  Title: "iOS Developer",
  Description: "iOS Developer",
  CompanyId: 1
}
Object {
  Id: 13,
  Title: "Sr. Android Developer",
  Description: "Sr. Android Developer",
  CompanyId: 1
}
Object {
  Id: 14,
  Title: "Sr. iOS Developer",
  Description: "Sr. iOS Developer",
  CompanyId: 1
}


问题是 typeahead 正在显示除
Sr 之外的所有结果。 Android 开发人员Sr。 iOS 开发者

var position = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.Title);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    //prefetch: '../data/films/post_1960.json',
    remote: {
        url: '/Search/Positions?query=%QUERY',
        wildcard: '%QUERY',
        filter:function (positionList) {
            // Map the remote source JSON array to a JavaScript object array
            return $.map(positionList, function (position) {
                console.log("position is:", position);
                return {
                    Title: position.Title
                };
            });
        }
    }
});
var promisepos=position.initialize();
promisepos.done(function(){});
$('#Position').typeahead({
    minLength:1,
    highlight:true,
    hint:false
},{
    name: 'positionList',
    displayKey:'Title',
    source:position.ttAdapter(),
    templates:{
        footer: "<div class='position-wrapper'><a class='ad-ps'><i class='fa fa-user-secret'></i> Add New Position</a></div>",
        notFound: function(){
            var ps=$('#Position').val();
            $('#PositionId').val("");
            return "<div class='position-wrapper'><p>No Position found.</p><a class='ad-ps'><i class='fa fa-user-secret'></i> Add New Position</a></div>";
        },
        suggestion: Handlebars.compile('<div class="position-wrapper">'+
                                        '<div class="poosition-info-wrapper">'+
                                            '<span>{{Title}}</span>'+
                                        '</div>'+
                                       '</div>')
    }
});

最佳答案

注意,不确定

的预期结果
$("#PositionId").val("");

? ; html 没有出现在问题中; .typeahead() 似乎在

初始化
$("#Position")

元素,在选择器字符串中没有“Id”?


The problem is typeahead is displaying all the result except Sr. Android Developer and Sr. iOS Developer

由于返回对象的 Title 属性的字符串值内的句点字符 . 出现。 .typeahead 似乎与 query 的输入值完全匹配。例如。,;如果查询是“sr”,.typeahead 将不匹配“Sr”。 ;如果查询是“sr”。 .typeahead 将匹配 "Sr. Android Developer"、 "Sr. iOS Developer"。在 Bloodhound 初始化时在 filter 函数中显示在 templates 中的返回匹配项的调整测试;删除句点字符“。”从结果返回到 templates 之前的匹配测试。如果查询是 "sr",应该同时返回 “高级 Android 开发人员”,“高级 iOS 开发人员”。如果查询是 "sr ios",应该将 "Sr. iOS Developer"返回到 templates 以显示为 suggestion

尝试创 build 置 Bloodhound.tokenizers.obj.whitespace"value" ;在 Bloodhound 初始化时将对象返回到 templates suggestion 回调函数中的 filter ;在 templates suggestion 回调函数中返回“suggestion” html,利用 Bloodhound< 中="">filter 传递的对象 初始化

$(function() {
    var search = $(".typeahead-container #Position.typeahead");
    // `positions` settings
    var positions = new Bloodhound({
      // set `Bloodhound.tokenizers.obj.whitespace` to `"value"`
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      remote: {
        url: "https://gist.githubusercontent.com/anonymous/"
             + "cd07af7c8e3dbbeb601f/raw/"
             + "936a69aa84e48c2cf96682ff044d3ace87750457/data.json"
             + "?query=%QUERY",
        wildcard: "%QUERY",
        filter: function (pos) {
          return $.map(pos, function(positions) {
            // return `value` set to `positions`:`data` `Title`,
            // return `suggest` property having value set to `positions` object,
            // utilized at `suggestion` callback
            // remove periof character "." from match test
            return new RegExp(
                     search.val() 
                     + "|" 
                     + search.val().replace(".", "")
                   , "i")
                   .test(positions.Title.replace(".", ""))                
                   ? {
                     value: positions.Title,
                     suggest: positions
                   } 
                   : null
          })
        }
      }
      /*  
      // run with "local" data source ; e.g., `data`
      local: $.map(data, function(positions) {
        return {
          value: positions.Tile,
          suggest: positions
        }
      })          
      */
    });
    
    var promisepos = positions.initialize();

    promisepos
    .done(function() {
      console.log("positions initialized");
    })
    .fail(function() {
      console.log("positions initialization error");
    });
    
    search.typeahead({
      minLength: 1,
      highlight: true,
      hint: false
    }, {
      name: "positionList",
      displayKey: "Title",
      templates: {
        // set `templates` `footer` `html`
        footer: "<div class=position-wrapper>"
                + "<a class=ad-ps><i class=fa fa-user-secret></i>"
                + " Add New Position</a></div>",
        // set `templates` `notFound` `html`
        notFound: function() {
                    // not certain expected result of calling `.val()`
                    // on `#Position` ?, without argument passed to `.val()` ?
                    var ps = $('#Position').val();
                    // not certain expected result of setting 
                    // `#PositionId` `.val()` to empty string ?
                    $("#PositionId").val("");
                    return "<div class=position-wrapper>"
                           + "<p>No Position found.</p>"
                           + "<a class=ad-ps>"
                           + "<i class=fa fa-user-secret></i>"
                           + " Add New Position"
                           + "</a></div>";
        },
        // set `templates` `suggestion` `html`
        suggestion: function(data) {
                      // `data`: `positions` object passed at
                      // `Bloodhound` `remote` `local`
                      var details = "<div class=resultContainer>" 
                                    + "Title: "
                                    + "<b style=color:blue>" 
                                    + data.suggest.Title 
                                    + "</b>" 
                                    + "<div class=resultDesc>" 
                                    + "Description: <b>" 
                                    + data.suggest.Description 
                                    + "</b>" 
                                    + "</div>"
                                    + "<div class=resultLabel>Id: "
                                    + "<b>" 
                                    + data.suggest.Id 
                                    + "</b><br />" 
                                    + "Company Id: " 
                                    + "<b>"
                                    + data.suggest.CompanyId 
                                    + "</b>"
                                    + "</div></div>";
                      return details

        }
      },
      source: positions.ttAdapter()
    });
});
/* 
// run with `local` data source
// `data`: `"data.json"` ; e.g., `data` at `local`
var data = [
  {
    "Id": 4,
    "Title": "project manager",
    "Description": "project manager",
    "CompanyId": 1
  },
  {
    "Id": 6,
    "Title": "Software Developer",
    "Description": "Software Developer",
    "CompanyId": 1
  },
  {
    "Id": 7,
    "Title": ".NET Developer",
    "Description": ".NET Developer",
    "CompanyId": 1
  },
  {
    "Id": 10,
    "Title": "Android Developer",
    "Description": "Android Developer",
    "CompanyId": 1
  },
  {
    "Id": 11,
    "Title": "iOS Developer",
    "Description": "iOS Developer",
    "CompanyId": 1
  },
  {
    "Id": 13,
    "Title": "Sr. Android Developer",
    "Description": "Sr. Android Developer",
    "CompanyId": 1
  },
  {
    "Id": 14,
    "Title": "Sr. iOS Developer",
    "Description": "Sr. iOS Developer",
    "CompanyId": 1
  }
];
*/
.typeahead-container {
  font-family: sans-serif;
  position: relative;
  margin: 100px;
}
.typeahead,
.tt-query,
.tt-hint {
  border: 2px solid #CCCCCC;
  border-radius: 8px;
  font-size: 24px;
  height: 30px;
  line-height: 30px;
  outline: medium none;
  padding: 8px 12px;
  width: 396px;
}
.typeahead {
  background-color: #FFFFFF;
}
.typeahead:focus {
  border: 2px solid #0097CF;
}
.tt-query {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
}
.tt-hint {
  color: #999999;
}
.tt-dropdown-menu {
  background-color: #FFFFFF;
  border: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
  margin-top: 12px;
  padding: 8px 0;
  width: 422px;
}
.tt-suggestion {
  font-size: 24px;
  line-height: 24px;
  padding: 3px 20px;
}
.tt-suggestion.tt-is-under-cursor {
  background-color: #0097CF;
  color: #FFFFFF;
}
.tt-suggestion p {
  margin: 0;
}
.resultContainer {
  width: 410px;
  border: 1px dotted grey;
  border-radius: 10px;
  padding: 4px;
  margin: 4px;
}
.resultDesc,
.resultLabel {
  font-size: 14px;
  font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js">
</script>
<input type="text" id="PositionId" />
<div class="typeahead-container">
  <input type="text" id="Position" class="typeahead tt-query" placeholder="positions" />
</div>

关于javascript - Bootstrap Typeahead 不显示 valueKey 以相同值开头的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30258673/

有关javascript - Bootstrap Typeahead 不显示 valueKey 以相同值开头的建议的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  4. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

  5. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  6. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  7. ruby-on-rails - 复数 for fields_for has_many 关联未显示在 View 中 - 2

    目前,Itembelongs_toCompany和has_manyItemVariants。我正在尝试使用嵌套的fields_for通过Item表单添加ItemVariant字段,但是使用:item_variants不显示该表单。只有当我使用单数时才会显示。我检查了我的关联,它们似乎是正确的,这可能与嵌套在公司下的项目有关,还是我遗漏了其他东西?提前致谢。注意:下面的代码片段中省略了不相关的代码。编辑:不知道这是否相关,但我正在使用CanCan进行身份验证。routes.rbresources:companiesdoresources:itemsenditem.rbclassItemi

  8. ruby-on-rails - 在 Flash 警报 Rails 3 中显示错误消息 - 2

    如果我在模型中设置验证消息validates:name,:presence=>{:message=>'Thenamecantbeblank.'}我如何让该消息显示在闪光警报中,这是我迄今为止尝试过的方法defcreate@message=Message.new(params[:message])if@message.valid?ContactMailer.send_mail(@message).deliverredirect_to(root_path,:notice=>"Thanksforyourmessage,Iwillbeintouchsoon")elseflash[:error]

  9. HBase Region 简介和建议数量&大小 - 2

    Region是HBase数据管理的基本单位,region有一点像关系型数据的分区。region中存储这用户的真实数据,而为了管理这些数据,HBase使用了RegionSever来管理region。Region的结构hbaseregion的大小设置默认情况下,每个Table起初只有一个Region,随着数据的不断写入,Region会自动进行拆分。刚拆分时,两个子Region都位于当前的RegionServer,但处于负载均衡的考虑,HMaster有可能会将某个Region转移给其他的RegionServer。RegionSplit时机:当1个region中的某个Store下所有StoreFile

  10. ruby-on-rails - Rails 4 WYSIWYG Bootsy 不显示格式 - 2

    我刚刚按照thebootsygempage上的安装说明进行操作在我保存并查看帖子内容之前,一切看起来都不错。这是输出在View中的样子:HeaderSubhead:似乎没有呈现任何html格式,因为它被引号或类似的东西转义了-其他人有这个问题吗?我没有在github页面或SO上看到任何问题来指出我正确的方向。除了遵循gem安装说明之外,我还没有做任何事情,但也许我错过了什么或者只是犯了一个愚蠢的错误。如果你还有什么想知道的,请尽管问。干杯 最佳答案 你需要有这样的东西,转义html: 关

随机推荐