在onKeydown函数中获取当前元素

时间:2013-07-12 09:00:28

标签: javascript jquery twitter-bootstrap

我正在编写一个函数,当按键在键盘上按下时将调用该函数如何访问按下该键的文本框的值。 我的代码是

function isValid(evt,that){

console.log('coming to this 1');
var charCode = (evt.which) ? evt.which : event.keyCode;
console.log(that.val());
return true;
}

$(document).on('keydown','.is_valid',isValid);

如何获取当前从键盘输入的文本框的值?请指南如何完成这个

5 个答案:

答案 0 :(得分:2)

我建议:

function isValid(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode,
        self = evt.target;
    console.log(self.value);
    return true;
}

$(document).on('keydown', '.is_valid', isValid);

JS Fiddle demo

只要该事件可用于该函数,您就可以使用具有适当名称的event.target访问该事件的目标。如果您需要将其作为jQuery对象,可以使用:$(event.target)来访问jQuery方法。

你也可以使用:

self = evt.currentTarget;

JS Fiddle demo

或者:

self = document.activeElement;

JS Fiddle demo

参考文献:

答案 1 :(得分:0)

您可以使用$(this)

获取当前元素
$(document).on('keydown','.is_valid',isValid){
alert($(this).val());

 //and  do stuff here 

}

答案 2 :(得分:0)

事件处理程序中的

this将指向目标元素

function isValid(evt,that){
    var charCode = (evt.which) ? evt.which : event.keyCode;
    console.log('log', $(this).val(), charCode);
    return true;
}

$(document).on('keydown','.is_valid',isValid);

演示:Fiddle

答案 3 :(得分:0)

that.val()更改为$(this).val()

function isValid(evt) {
    console.log('coming to this 1');
    var charCode = (evt.which) ? evt.which : event.keyCode;
    console.log($(this).val());   // change that to $(this)
    return true;
}

$(document).on('keydown', '.is_valid', isValid);

运作良好。查看JSFiddle

答案 4 :(得分:0)

有几种不同的方法可以解决这个问题。以下是三个例子:

function isValid(evt) {
    // if you use 'this', you don't need to pass 'evt' to the function
    console.log(this.value);

    // you can reference the event target
    console.log(evt.target.value);

    // you can reference the event's current target
    console.log(evt.currentTarget.value);

    return true;
}

$(document).on('keydown', '.is_valid', isValid);

这些都会为您提供文本框的价值。

如果您想查看可能的其他选项,console.log(evt);

相关问题