Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

How can i create an array if it doesn't exist and run a jquery function after it creates an array?

I have a fiddle.

I want to be able to check if an array exists. If it does not exist i need to create it and run a this function.

$('p').live('click', function(){
    $('p').html('yay, it worked! Thankyou!')
}  

That does not work and i know that but i do not know how to check it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a normal if statement instead of the conditional operator:

if(!$.isArray(x)) {
    x = [];
    $('p').live('click', function(){
        $('p').html('yay, it worked! Thankyou!')
    });
}

Note: x must be at least declared (var x;) for this to work.

Reference: if...else, jQuery.isArray

Update: Reading the comments on the other (now deleted answer), did you intend to do something like this?

function doStuff() {
    $('p').html('yay, it worked! Thankyou!');
}

$('p').live('click', doStuff);

if(!$.isArray(x)) {
    x = [];
    doStuff();
}

It's not really clear given the information you provided. You just said run this function and posted a snippet which lets assume that the whole snippet is the code you want to run when the array is created. Please be more precise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...