需要模拟按键jquery

时间:2016-06-21 16:06:16

标签: javascript jquery

我有一个函数,它使用文本框(prodinput)的值来隐藏/显示下拉列表中的链接。当用户手动键入字符串但当我想通过传递url参数自动填充值时,它会工作,我需要触发keyup或keydown来调用该函数。

以下是执行搜索的功能(位于core.js中):

prodinput.on('keyup, keydown',function() {
    var search = $(this).val().toLowerCase();
    $('.support-product .browse-products a').each(function() {
        if($(this).text().toLowerCase().search(search) > -1) {
            $(this).parent().show();
        } else {
            $(this).parent().hide();
        }
    });
});

以下是我用来触发上述功能的功能(位于页面上我尝试运行它。

$(function(){
                $target = $('.browse-products .display');
                $target.val($trimmed);
                $('.browse-products').addClass('active');
                $target.focus();
                var e = jQuery.Event( "keydown" );
                $target.trigger(e);
            });

我尝试过使用:

$target.keyup();

并如上所示:

var e = jQuery.Event( "keydown" );
$target.trigger(e);

我想知道在网页上加载内容的顺序是否存在问题。

2 个答案:

答案 0 :(得分:0)

我将你的密钥代码放在一个命名函数中。

$(function () {
    myFunction();
    prodinput.on('keyup, keydown', function () {
        myFunction();
    })
};

var myFunction = function () {
    var search = $('#prodinput').val().toLowerCase();
    $('.support-product .browse-products a').each(function () {
        if ($(this).text().toLowerCase().search(search) > -1) {
            $(this).parent().show();
        } else {
            $(this).parent().hide();
        }
    });
};

答案 1 :(得分:-1)

假设您不需要支持古老的浏览器,您可以只听取涵盖按键和更改事件的<dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>${jettyVersion}</version> </dependency> <dependency> <groupId>org.apache.solr</groupId> <artifactId>solr-solrj</artifactId> <version>6.0.1</version> </dependency> 事件。然后在附加监听器后,只需触发事件:

input
$(function() {
  $("#prodinput").on('input', function() {//alternatively you could use change and keyup
    var search = $(this).val().toLowerCase();
    $('.support-product .browse-products a').each(function() {
      if ($(this).text().toLowerCase().search(search) > -1) {
        $(this).parent().show();
      } else {
        $(this).parent().hide();
      }
    });
  }).trigger("input");//trigger the event now
});