开发者

Passing elements as variables to function

开发者 https://www.devze.com 2023-02-12 02:23 出处:网络
I\'m having an issue with an element object and a jQuery function: HTML <labelfor=\'state\'>State</label>

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

HTML

<label  for='state'>State</label>
<input  id='state' name='st开发者_StackOverflow社区ate' 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))

should also work (see http://ejohn.org/apps/learn/#26)

0

精彩评论

暂无评论...
验证码 换一张
取 消