【问题标题】:Calling a function everytime user types每次用户输入时调用一个函数
【发布时间】:2016-05-04 09:48:11
【问题描述】:

我有以下功能,我想每次都被调用,用户在typeahead输入字段中输入一些内容。

function getAllActiveUsers() {
    var userList = $('#usersTable').jqGrid('getGridParam').userData;
    var userNames = {};
    if(userList) {
        // Return the list  of all active users
        $(userList).each(function() {
            if(this.userStatus != 1) {
                // If the user is verified
                // Could be active/inactive
                userNames.user = this.username;
            }
        });
    }
    return JSON.stringify(userNames);
}

HTML:

 <div id="the-basics">
   <input class="typeahead" type="text" data-provide="typeahead" placeholder="User List">
</div>

我一直在浏览examples,但不明白如何实现此功能。

编辑

为什么当我初始化为时它不起作用:

$('.typeahead').typeahead({
    source : getAllActiveUsers
});

【问题讨论】:

  • 调用$('.typeahead').on('keyup',getAllActiveUsers())上的函数试试这个
  • 您使用的是哪种类型的预输入?您指的是 typehead.js,但有些东西告诉我您使用的是不同的?
  • getAllActiveUsers 返回什么?

标签: javascript jquery typeahead.js typeahead bootstrap-typeahead


【解决方案1】:

试试这个

$(document).ready(function(){
   $('.typeahead').keyup(function(){
       getAllActiveUsers();
   });
});

【讨论】:

  • 为什么要使用匿名函数?那是冗余。
【解决方案2】:

你可以使用.keyup jquery函数

$( ".typeahead" ).keyup(function() {
  getAllActiveUsers();
});

【讨论】:

  • 为什么要使用匿名函数?那是冗余。
  • 你是对的。匿名函数可以只替换为需要执行的函数。但它更容易阅读。
  • 它不起作用。我正在尝试使用twitter's typeahead。
  • 我没用过那个插件,但我想你给它提供了错误格式的数据。
【解决方案3】:

取自您提供的参考资料,您可以在 id #the-basics 内指定类 .typeahead

$(document).ready(function(){
  $('#the-basics .typeahead').typeahead({
    //code here;
  }
}

由于在文档准备好之前无法安全地操作页面,因此您应该使用$(document).ready
另外,尝试使用您的浏览器控制台并检查您是否可以访问$('#the-basics .typeahead')

【讨论】:

    【解决方案4】:

    您可以使用 Jquery Keyup,它会在释放键时触发。

    $( ".typeahead" ).on('keyup',function() {
      getAllActiveUsers();
    });
    

    【讨论】:

      【解决方案5】:

      如果你的文本框是动态的,那么你应该尝试

      $(document).on("keyup", ".typeahead" , function() {
        getAllActiveUsers();
      });
      

      试试这个,让我们知道它是否有效。

      【讨论】:

        【解决方案6】:

        应该可以

        var getAllActiveUsers = function(q, cb, cb2) {
          // cb for sync, cb2 for async
          var userList = $('#usersTable').jqGrid('getGridParam').userData;
          var filterted = /* whatever you want to do with q */;
          cb(filtered);
        };
        
        $('.typeahead').typeahead({
            /* Options */
        },
        {
            source : getAllActiveUsers
        });
        

        【讨论】:

          猜你喜欢
          • 2018-11-26
          • 2019-11-18
          • 1970-01-01
          • 2021-11-15
          • 1970-01-01
          • 2018-06-17
          • 1970-01-01
          • 2016-05-02
          • 2011-07-12
          相关资源
          最近更新 更多