我有一个JQuery代码,它将引用(在单击按钮时随机生成)传递给twitter。但是,当您打开新窗口以发布推文时,它会显示未定义的值,与实际报价相反。
以下是代码:
$(document).ready(function(){
var result;
function getQuotes(){
var quotes = [ "Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.-\n Buddha",
"Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.\n-Unknown",
"To be happy, we must not be too concerned with others.\n-Albert Camus",
"If you want happiness for an hour — take a nap.If you want happiness for a day — go fishing.If you want happiness for a year — inherit a fortune.If you want happiness for a lifetime — help someone else."]
var result = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("stuff").innerHTML = result;
}
$("#tweet").on('click',function(){
window.open("http://www.twitter.com/intent/tweet?text="+result);
});
$(document).on('click', '#quotes', function() {
getQuotes();
});
});
以下是codepen的链接:http://codepen.io/sibraza/pen/KMPzxx?editors=1010
答案 0 :(得分:2)
由于使用result
两次,您有两个不同的var
变量。唯一获得值集的是getQuotes()
在getQuotes()
之外声明的其他内容始终未定义。
尝试更改
var result = quotes[Math.floor(Math.random() * quotes.length)];
要
result = quotes[Math.floor(Math.random() * quotes.length)];