我在获取 jQuery 回调函数中的元素时遇到问题。我尝试了 $(this) 和 $(this.element) 的各种建议但没有成功。
$.fn.onTypeFinished = function (func) {
$(this).bind("keypress", onKeyPress)
function onKeyPress() {
setTimeout(onTimeOut, 500);
}
function onTimeOut() {
func.apply();
}
return this;
};
$(".user-input").onTypeFinished(function () {
var ntabindex = parseFloat($(this.element).attr('tabindex'));
ntabindex++;
$('input[tabindex=' + ntabindex + ']').focus();
});
我一直在想我需要一些方法来将对此的引用传递给回调函数,但似乎没有其他类似的帖子建议该路由。
这是我正在尝试做的 JSFiddle。该功能的要点是我正在尝试根据 tabindex 自动前进到下一个输入。
http://jsfiddle.net/helfon/fdu8xw0h/2/
谢谢
最佳答案
从您的代码看来,您想将发生按键的元素作为 this
传递给回调。
为此,您需要将正确的上下文传递给 timeout
处理程序,为此我们可以使用 .bind(),如下所示。
此外,为了使计时器正常工作,还进行了一些其他更正。
$.fn.onTypeFinished = function(func) {
$(this).bind("keypress", onKeyPress)
function onKeyPress() {
var onTypeFinished = $(this).data('onTypeFinished');
if (!onTypeFinished) {
onTypeFinished = {};
$(this).data('onTypeFinished', onTypeFinished);
}
clearTimeout(onTypeFinished.keytimer);
onTypeFinished.keytimer = setTimeout(onTimeOut.bind(this), 500);
}
function onTimeOut() {
func.apply(this);
}
return this;
};
$(".user-input").onTypeFinished(function() {
//$('input[tabindex=3]').focus();
var ntabindex = parseFloat(this.getAttribute('tabindex'));
ntabindex++;
$('input[tabindex=' + ntabindex + ']').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="1" tabindex=1 class="user-input">
<input id="2" tabindex=2 class="user-input">
<input id="3" tabindex=3 class="user-input">
<input id="4" tabindex=4 class="user-input">
关于javascript - 在 JQuery 回调中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31945004/