【问题标题】:Add keypress or eventlistener to input, "TypeError: ...addEventListener is not a function"将按键或事件监听器添加到输入,“TypeError: ...addEventListener 不是函数”
【发布时间】:2016-04-22 04:40:41
【问题描述】:

我正在处理一个我不想输入/返回提交表单的表单,所以我使用了这样的函数。

    $('[name="form"]').keypress(function(e) {
        var charCode = e.charcode || e.keyCode || e.which;
        if (charCode === 13) {
            e.preventDefault();
            return false;
        }
    });

这行得通,但现在我想分配输入/返回以对表单上的两个输入执行功能。我完全被困住了。

为了获得输入,我尝试过通过 id 调用 vanilla js,通过 id 调用 jQ,然后将两者与变量混合。我也尝试过 .keypress、.keydown、.keyup 而不是 attachEventListener 方法。无论我做什么,我都会在控制台中收到此错误。

“TypeError: ...addEventListener 不是函数”(或 keypress、keydown 等)

我也研究了很多,但找不到任何解决方案。我很感激任何建议。 这是当前形式的代码块,它给了麻烦。

    var yelpInput = $('#inputURL');
    var googleInput = $('#googleURL');

    yelpInput.addEventListener("keydown", function(e) {
        if (e.keyCode === 13 ) {                        
            alert('do stuff!');
        }
    });

    // Google
    googleInput.addEventListener("keydown", function(e) {
        if (e.keyCode === 13 ) {    
            alert('do stuff!');
        }
    });

谢谢

【问题讨论】:

  • yelpInputgoogleInput 是 jquery 对象而不是 dom 对象。
  • 我还尝试通过 document.getElementById('yelpInput'); 获取输入等等,并得到同样的错误。
  • 奇怪。这似乎有效:jsfiddle.net/subterrane/0rkgdd4w

标签: javascript jquery forms keypress addeventlistener


【解决方案1】:
var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');

yelpInput.keydown(function(e) {
    if (e.keyCode === 13 ) {                        
        alert('do stuff!');
    }
});

// Google
googleInput.keydown(function(e) {
    if (e.keyCode === 13 ) {    
        alert('do stuff!');
    }
});

【讨论】:

  • 谢谢,我之前用过keydown的方法,还是不行。我一定是搞砸了,因为现在可以了。
【解决方案2】:

yelpInputjQuery 包装的对象,它没有 addEventListener 方法。

使用.onevent-handler 附加到jQuery 包装对象或yelpInput[0].addEventListener/yelpInput.get(0).addEventListener 使用JavaScript 附加事件,因为yelpInput[0] 将是DOMElement 而不是jQuery-wrapped 对象。

var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');

yelpInput.on("keydown", function(e) {
  //-----^^^
  if (e.keyCode === 13) {
    alert('do stuff!');
  }
});
googleInput.on("keydown", function(e) {
  //-------^^^
  if (e.keyCode === 13) {
    alert('do stuff!');
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    相关资源
    最近更新 更多