将元素作为变量传递给函数

Jam*_*ars 2 javascript jquery

我遇到了元素对象和jQuery函数的问题:

HTML

<label  for='state'>State</label>
<input  id='state' name='state' type='text' value=''/>
<span class='info'><img class='tick' /><img class='cross' /></span>
Run Code Online (Sandbox Code Playgroud)

JavaScript/jQuery

var state = $("#state");

function validatefield(myelement) {
    if (myelement.val().length > 3) {
        alert("word");
    } else {
        alert("sup");
    }
}
state.blur(validatefield(state));
state.keyup(validatefield(state));
Run Code Online (Sandbox Code Playgroud)

页面加载时没有任何反应,即使状态输入的字符数超过3个.

有任何想法吗?

太棒了 - 学习新东西ftw

And*_*y E 6

根本不需要参数,事件处理程序绑定到元素,以便您可以this在函数内使用关键字:

var state = $("#state");

function validatefield(event) {
    if (this.value.length > 3) { // <-- use `this.value` instead
        alert("word");
    } else {
        alert("sup");
    }
}
state.blur(validatefield);
state.keyup(validatefield);
Run Code Online (Sandbox Code Playgroud)

你尝试它的方式实际上会调用函数并使用它的返回值作为事件处理程序,这就是为什么没有发生的事情:

// validatefield(state) is executed immediately and the return value, "undefined"
// is passed as the first argument to state.blur()
state.blur(validatefield(state));
Run Code Online (Sandbox Code Playgroud)

要修复this关键字不可用的其他情况,您应该使用匿名函数:

state.blur(function () { validatefield(state) });
Run Code Online (Sandbox Code Playgroud)