简体   繁体   中英

function call with argument in jquery

I have included an external javascript file whose contents are:

function getTopNews(){
  $.ajax({
    url: 'http://api.feedzilla.com/v1/categories/26/articles.json',
    type: 'GET',
    dataType: 'json',

    success: function(response){
        alert("Got top news!");
    },

    error: function(){
        alert("There was an error!");
    },

    complete: function(){
        alert('Executed');
    }
  });
}

Now the above javascript file is included in another file where I have written this code:

$(document).ready(getTopNews);  // works

Now suppose my getTopNews is defined like getTopNews(var newsId), then how should I call it? I have tried following and it does not work:

$(document).ready(getTopNews(26));  // does not work

$(document).ready(fucntion(){  // does not work
  $(this).getTopNews(26)
});

Both of these do not work for me. Help!

What abt this ? getTopNews isnt an object of document so it wont come under $(this) :

$(document).ready(function(){
  getTopNews(26);
});

"Now suppose my getTopNews is defined like getTopNews(var newsId) "

Then what you'd have is a syntax error and the code wouldn't work. Remove the var :

function getTopNews(newsId) {
   // your code here
}

To call that on ready, do this:

$(document).ready(function(){
  getTopNews(26);
});

Note that in your code when you did something similar you had a typo on this line:

$(document).ready(fucntion(){  // does not work

...where you spelled function as fucntion .

Note that both problems should've been reported in your browser's console.

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