簡體   English   中英

調用時無法執行Javascript函數

[英]Javascript function does not execute when called

我有以下代碼:

function firstQuote(){
  jQuery.ajax({
    url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
    type: 'GET',
    dataType: "jsonp",
  }); 

  function mycallback(json){
    document.getElementById('quote').innerHTML = json[0].content;
  }
};
window.onload = firstQuote;

這是一個簡單的函數,但未執行。 如果我將代碼放在函數之外,則可以正常工作。 我現在堅持了一段時間。 拜托,有人可以幫我嗎?

您正在嘗試在firstQuote函數中定義回調。 (如果您查看錯誤控制台,則會看到“ [Error] ReferenceError:找不到變量:mycallback”。)將這些函數分開,以將mycallback放在全局范圍內:

 function mycallback(json) { document.getElementById('quote').innerHTML = json[0].content; } function firstQuote() { jQuery.ajax({ url: "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback", type: 'GET', dataType: "jsonp", }); }; window.onload = firstQuote; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="quote"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM