2017-06-13 101 views
1

我使用jQuery代码通过使用回车键来触发输入字段。我在另一个视图中使用了代码,它的工作非常完美。在新观点中,它根本不起作用。 keyup被触发,但不调用.bind()函数。 这里的HTML触发:带.bind()的jQuery .keyup()不起作用

<div class="form-group"> 
    <h3>Customers</h3> 
    <input class="form-control" id="searchNew" placeholder="Search" name="searchNew" autofocus="" value="@form("searchValue").value"> 
</div> 

这是jQuery代码:

$('#searchNew').bind("enterKey", function(e){ 
      console.log("Test2"); 
      $.ajaxSetup({ 
       beforeSend: function(){ 
        $('.loading').fadeIn(); 
       }, 
       complete:function(){ 
        $('.loading').fadeOut(); 
       } 
      }); 
      $.ajax({ 
       type : 'POST', 
       url : '@routes.Application.searchLicensesAdmin()', 
       data : $('#search').serialize(), 
       success : function (data) { 
        $('#license-table').html(data); 
        return false; 
       }, 
       error : function (data) { 
        console.log("Error"); 
       } 
      }); 
      return false; 
     }); 
     $('#searchNew').keyup(function(e){ 
      if(e.keyCode == 13){ 
       console.log("Test1"); 
       $(this).on("enterKey"); 
      } 
     }); 

Test1的被触发并在控制台中显示出来,但Test2的甚至没有触发的。所以问题不在于拨打ajax,而是拨打.bind()。这可能是一个愚蠢的原因,为什么它不起作用,但我无法弄清楚。 jQuery包含在两个文档中。

回答

3

你需要$(this).trigger('enterKey')

.bind().on()做的差不多,虽然.bind()从版本3开始已弃用(所以不要使用它;))。

声明$(this).on('enterKey')刚刚注册了一个新的事件监听器,用空/未定义的回调

2

你想触发自定义事件

变化

$(this).on("enterKey"); 

$(this).trigger("enterKey"); 
0

尝试。

$(this).trigger("enterKey"); 

建议不要使用.bind(),因为它已被弃用。