传递变量参数的jQuery
问题描述:
HTML传递变量参数的jQuery
<input type="text" id="test" />
<span>0</span>
jQuery的
var input = $('input#test');
input.bind('keyup', function() {
doThis();
});
input.on('input', function() {
doThis();
});
function doThis() {
var wordCounts = {};
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length/2 : 0;
var finalCount = 0;
$.each(wordCounts, function(k, v) {
finalCount += v;
});
$('span#word-count').text(finalCount);
}
的jsfiddle:http://jsfiddle.net/YJVPZ/265/
眼下doThis()
甚至不工作。如果我将doThis()
的内容与input.bind('keyup', function() { ... }
包装在一起,它就可以正常工作。我知道这是因为它使用了未定义的this
。我如何通过变量input
作为参数?
有什么方法可以使用.bind和.on来调用相同的函数,而不是像我现在那样调用两个单独的实例吗?
答
input.bind('keyup input', doThis);
通过传递函数来.bind
/.on
jQuery的自动设置this
参考的处理程序来触发元件的内部,所述事件处理程序(在这种情况下,#test
)。
要设置手动this
参考,这是在这种情况下没有必要的,你会使用Function.call
/Function.apply
:
input.bind('keyup input', function() {
//in this scope, `this` points to `#test`
doThis.apply(this, arguments); //sets `this` inside of this `doThis` call to
//the same `this` of the current scope.
});
我们应用arguments
使doThis
也接收传递给Event object事件处理程序。在这个特定用例中不是必需的,但在代理需要访问传递给原始处理程序的参数的事件处理程序时非常有用。
侧面说明:为了您的代码工作,你应该把它移动到body
年底或紧裹DOM ready handler的内部代码,也就是把它里面的$(function(){/*code here*/});
答
试试这个 -
input.on('input keyup', doThis);