开发者

JQuery function as var, and then executing var on action

I have a function:

var oneWay = function (){
    $(".one-way").show();
    $(".round-trip").hide();
    $(".multi-stop").hide();
 };

I want to trigger this function on an action, i.e.:

$开发者_开发技巧(document).ready(function(){
    $("input:radio[value=one-way]").click('oneWay');
});

But this isn't working. I think my syntax might be off.

Also, what if I wanted to just execute this function when the DOM is ready? Would it be this:

$(document).ready(function(){
   oneWay; 
});

Thanks, Brian


Removing the quotes should be enough...

$(document).ready(function(){
    $("input:radio[value=one-way]").click(oneWay);
});


Exactly what DavidGouge said. Further, to answer your other question, you just do this:

$(document).ready(function(){
    $("input:radio[value=one-way]").click(oneWay); //binds it to the click event
    oneWay(); //executes it now.
});

Remember that oneWay is a reference to a function (passed as an "object"), while oneWay() executes that function immediately.


$(document).ready(function(){
    $("input:radio[value=one-way]").click(oneWay);
});

or

$(document).ready(function(){
    $("input:radio[value=one-way]").click(function(){ oneWay(); });
});

and the last:

$(document).ready(function(){
   //oneWay;
   oneWay(); 
});


Click takes as it's argument a function literal, not a string name of a function literal.

See a working example.

And the pertinent modification:

$(document).ready(function(){
    $("input:radio[value=one-way]").click(oneWay); // no quotes here, just the variable
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜