简体   繁体   English

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

[英]Passing elements as variables to function

I'm having an issue with an element object and a jQuery function: 我遇到了元素对象和jQuery函数的问题:

HTML HTML

<label  for='state'>State</label>
<input  id='state' name='state' type='text' value=''/>
<span class='info'><img class='tick' /><img class='cross' /></span>

JavaScript / jQuery 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));

Nothing happens on page load, even when state has more than 3 chars entered. 页面加载时没有任何反应,即使状态输入的字符数超过3个。

Any ideas? 有任何想法吗?

Awesome - learning new stuff ftw 太棒了 - 学习新东西ftw

No need for arguments at all, the event handler is bound to the element so that you can use the this keyword inside the function: 根本不需要参数,事件处理程序绑定到元素,以便您可以在函数内使用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);

The way you're attempting it will actually call the function and use its return value as the event handler, which is why nothing was happening: 你尝试它的方式实际上会调用函数并使用它的返回值作为事件处理程序,这就是为什么没有发生的事情:

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

To fix other situations like this where the this keyword is not available, you should use an anonymous function: 要修复this关键字不可用的其他情况,您应该使用匿名函数:

state.blur(function () { validatefield(state) });

Wrap the function calls in anonymous functions. 将函数调用包装在匿名函数中。

$(document).ready(function(){
    var state = $("#state");
    state.blur(function() {validatefield(state)});
    state.keyup(function() {validatefield(state)});
});

http://jsfiddle.net/eW8E8/1/ http://jsfiddle.net/eW8E8/1/

You should use an anonymous function as jQuery event handler, instead of 您应该使用匿名函数作为jQuery事件处理程序,而不是

state.keyup(validatefield(state));

use 采用

state.keyup(function() {
  validatefield(state);
});

Shouldnt it be: 不应该是:

if(myelement.value.length > 3) { if(myelement.value.length> 3){

state.keyup(validatefield.call(this, state))

也应该有效(见http://ejohn.org/apps/learn/#26

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM