【问题标题】:jquery draggable input cannot detect keydown / input anythingjquery可拖动输入无法检测到keydown /输入任何内容
【发布时间】:2018-07-03 14:06:17
【问题描述】:

我正在编写一个可拖动的 html div 为:

它看起来像这样:

但是我不能输入像普通输入 div 这样的东西:<input />。 它不响应任何关键事件。

我已尝试使用stopPropagation 将事件停止给它的父母:

    input.onclick = function ( evt ) {
        evt.stopPropagation();
        console.log( 'input got clicked' );
    };


    $( input ).on( 'keydown', function ( evt ) {
        evt.stopPropagation();
        console.log( 'input got keydown' );
    } );

input 在哪里:

    let input = document.createElement( 'input' );
    input.setAttribute( 'type', 'text' );

console.log( input ):

但这无济于事。 (而对于后面的 keydown 事件,控制台中不会给出任何输出。)

谁能建议我调试这个问题的方法?它真的让我发疯。谢谢!

PS:使用的是 Chrome。

更新:我找到了问题,但不知道原因。

是因为我把父dom装饰成jquery draggable,需要取消<input class='x-leaf'/>为:

    $('#input-parent').draggable({
        containment: 'window',
        cancel: '.x-leaf'
    });

用之前的stopPropogation和@Brainfeeder建议的方式,终于奏效了。

【问题讨论】:

  • 向我们展示您如何在$( input ) 中定义input
  • $('input')
  • @Cruiser 正确,除非他已将输入定义为变量,如果已定义,仍应以其他方式完成
  • 您一定遇到了错误,input in not defined
  • 感谢您的回复。 input 是一个变量,我在问题中对其进行了编辑。

标签: javascript jquery html css dom


【解决方案1】:

因为输入是在 DOM 加载后创建的,所以您最好在页面加载时对 DOM 中存在的父元素调用 .on()。

$('#someParentEl').on( 'keydown', '.x-node input', function ( evt ) {
    console.log( 'input got keydown' );
} );

【讨论】:

  • 尝试将$(input) 更改为.x-node input 或一些匹配输入而不是对象的选择器。
  • ` $( document ).on( 'keydown', $( '.x-node input' ), function ( evt ) { evt.stopPropagation(); console.log( 'input got keydown ' ); } );`
  • 感谢您的耐心等待。我已经用上面的代码检测到了这个事件。但我仍然无法输入任何内容。
  • 真正奇怪的是,一旦我添加了这个input.classList.add('x-connection');,它就可以工作了,即使是我以前的错误代码。
  • .x-connection{ position:absolute; border:solid 1px #dedede; background-color:#2e2e2e; width:0.5em; height:0.5em; border-radius:0.5em; }
猜你喜欢
  • 2012-12-31
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2021-12-17
  • 2011-07-25
  • 2011-01-26
  • 2021-03-23
  • 2015-10-05
相关资源
最近更新 更多