简体   繁体   中英

Passing elements as variables to function

I'm having an issue with an element object and a jQuery function:

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

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.

Any ideas?

Awesome - learning new stuff 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:

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:

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/

You should use an anonymous function as jQuery event handler, instead of

state.keyup(validatefield(state));

use

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

Shouldnt it be:

if(myelement.value.length > 3) {

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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