dpwtr666638 2013-07-18 10:24
浏览 42

包含一个可以查看JSON并返回下拉列表的搜索框

I'm using a JSON file to populate some drop down menus for various conversions. The converter has grown somewhat and I'd like to have the option of including a search bar.

So a user can search for Milliampere instead of navigating to the 'Current' category within "Electricity" etc etc. I'd just like to make it a bit easier for them.

My JSON only has two fields, the name and value of the drop down, example below. The value is a string in the fashion that I understand so that Milliampere is milliAmpere and various others all using camel case. I don't think it would be suitable to run the search on this field as the values may differ from the name.

The name field in this instance is Milliampere(mA) so I need for the search to be able to look at part of the string and not do a full match ignoring case as the liklihood is the search string would be milliamp or milliampere or even milliamperes.

From there the next step is either to populate the drop downs whilst on that page or to return a list of possible options if there are many.

Is this possible at all and if so can you please guide me in the right direction?

Many thanks!

    "current":[
    {
        "value" : "ampere",
        "name" : "Ampere(A)"
    },
    {
        "value" : "kiloAmpere",
        "name" : "Kiloampere(kA)"
    }]
  • 写回答

1条回答 默认 最新

  • dstwfcz1377 2014-01-07 08:03
    关注

    You can use this JS lib - DefiantJS (defiantjs.com), which extends the global object JSON with a new method: "search". With this method, you can search a JSON structure with XPath expressions, like this:

    var data = {
           "current": [
              { "value": "ampere",      "name": "Ampere(A)" },
              { "value": "kiloAmpere",  "name": "Kiloampere(kA)" },
              { "value": "milliAmpere", "name": "milliAmpere" },
              { "value": "Milliampere", "name": "Milliampere" }
           ]
        },
        res = JSON.search( data, '//name[contains(translate(., "MA", "ma"), "millia")]/..' );
    
    console.log( res[0].name );
    console.log( res[1].name );
    

    The "translate" method in the expression extends the search to include uppercase and lowercase versions of the letters "ma". If you want to cover all the alphabetic letter, then add all of them.

    Here is a working fiddle;
    http://jsfiddle.net/hbi99/6ssS9/

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据