Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 为什么第一个条件不起作用?_Jquery_Api_If Statement - Fatal编程技术网

Jquery 为什么第一个条件不起作用?

Jquery 为什么第一个条件不起作用?,jquery,api,if-statement,Jquery,Api,If Statement,好的,我想通过APIforismatic.com获得随机引用,如果它有140个字母,我想通过推特分享。我的问题是,因为我不确定,为什么第一个条件不起作用 var tweetLink = "https://twitter.com/intent/tweet?text="; var quoteUrl = "http://api.forismatic.com/api/1.0/?method=getQuote&key=867576&format=jsonp&lang=en&

好的,我想通过APIforismatic.com获得随机引用,如果它有140个字母,我想通过推特分享。我的问题是,因为我不确定,为什么第一个条件不起作用

var tweetLink = "https://twitter.com/intent/tweet?text=";
var quoteUrl = "http://api.forismatic.com/api/1.0/?method=getQuote&key=867576&format=jsonp&lang=en&jsonp=?";
function getQuote() {
$.getJSON(quoteUrl, createTweet);
}
function createTweet(input) {
if (tweetText.length > 140) {
getQuote();}


var tweetText = "Quote of the day - " + input.quoteText + " Author: " +   input.quoteAuthor;}
     if (!input.quoteAuthor.length) {
    input.quoteAuthor = "Unknown author";

 else {
var tweet = tweetLink + encodeURIComponent(tweetText);
$('.quote').text(input.quoteText);
$('.author').text("Author: " + input.quoteAuthor);
$('.tweet').attr('href', tweet);
}
}
  $(document).ready(function() {
getQuote();
$('.trigger').click(function() {
    getQuote();
})
});

如果我没弄错你的问题,你说这个条件不起作用

if (tweetText.length > 140) {
当然,您的浏览器的调试控制台正在告诉您这里的问题。此处未定义tweetText变量。因为您在使用它之后定义了它:

if (tweetText.length > 140) {
    getQuote();
}
var tweetText = "Quote of the day - " + input.quoteText + " Author: " + input.quoteAuthor; 
简单地说,在拥有值之前不能使用值。你肯定想把这两个操作放在相反的顺序上:

var tweetText = "Quote of the day - " + input.quoteText + " Author: " + input.quoteAuthor;
if (tweetText.length > 140) {
    getQuote();
}
首先定义变量,然后使用变量


请注意,您的代码中可能还有其他错误,但仅从查看代码就很难判断,除非您更合理地构造代码。请记住,代码不仅仅意味着执行,它还意味着人类可以阅读和理解。包括你。您可以阅读和理解的代码将更易于调试。

您忘记了描述问题并询问有关该问题的问题的部分。至于代码审查,第一个建议是合理地格式化代码。好的,对不起,我是新手。我更正了,我希望现在更清楚。您的编辑没有向问题添加任何信息,因此没有澄清任何内容。所以你有一个版本可以工作,一个版本出错,你问这两个版本中哪一个可以使用?我想最好是能用的。如果你想问一些更具体的问题,你在问题中没有问过,也没有描述过,我也不理解这个问题。您似乎在许多不同的地方调用getQuote,对吗?如果您首先使用该语句,您会得到一个错误,因为它在分配给tweetText之前。