在模态对话框中检测按键操作无效

3
我希望在模态框弹出时能检测用户是否按下了任何键。我尝试了以下代码,但事件并未触发。

代码片段:

   $("#modal_confirmation_dp_change").on('keydown keyup input', function ( e ) {
         alert();
        });

如果我尝试测试点击事件,它会被触发。

   $("#modal_confirmation_dp_change").on('click', function ( e ) {
            alert();
        });

我正在使用Twitter Bootstrap模态框,是否有遗漏的部分?

答案: 我找到了解决方法。看起来我不应该指向模态框的id,这样按键事件就会被检测到。


模态框是如何创建的?你是否在事件中设置了断点以查看它是否被触发? - BenG
我正在使用 Twitter Bootstrap 模态框。我尝试在该函数中设置断点,但它没有被触发。另一方面,点击事件是被触发的。 - Marss
请查看以下链接:https://dev59.com/UZLea4cB1Zd3GeqPySFg#34316271,这可能会有所帮助。 - BenG
你能放上你的HTML代码吗? - Abdelhak
3个回答

4
我找到了我的问题的解决方案。看来我不应该指向模态框的ID,这样按键事件才能被检测到。
$(document).on('keydown keyup input click',  function (e) {
if($('#modal_confirmation_dp_change').is(':visible')) {
            var key = e.which;
                if (key == 13) { //This is an ENTER 
                    $('#changed_dp_ok').click();
                }
        }
    });

1

您不应该像这样使用多个事件,因为它将根据您的事件计数触发三次,一次为keydown,一次为keyup,一次为input。尽管如此,这并不是问题,问题在于您正在触发click事件。那是 jQuery 事件对象的事件,而您需要在 DOM 上触发click

你应该触发 DOM 的本地 .click() 事件:

$("#modal_confirmation_dp_change").on('keydown', function ( e ) {
    var key = e.which || e.keyCode;
    if (key == 13) {
        $('#changed_dp_ok')[0].click(); // <----use the DOM click this way!!!
    }
});

$(document).on('keydown', function(e) {
  if (e.which == 13) {
    //$('.btn').click();  // <----this wont work
    $('.btn')[0].click(); // <---but this works
  }
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>


检查添加的代码片段。 - Jai

0

我认为将焦点放在模态框上是更好的解决方案。

为了实现这一点,您需要向模态框容器添加一个tabindex参数,然后使用JavaScript设置其焦点。完成后,它就可以接收键盘事件:https://dev59.com/dWw15IYBdhLWcg3wZ68Y#6633271


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接