一些背景:我正在完成 FreeCodeCamps 前端开发项目,这个项目代表一个随机报价机。
我想隐藏每个引用的作者,但目前,“点击显示”按钮只会显示每隔一个引用的作者...
https://codepen.io/DecisiveIndecisive/pen/KXjXXd
有问题的代码是 Javascript。谢谢!
$(document).ready(function() {
var url =
"https://api.forismatic.com/api/1.0/?method=getQuote&key=1&lang=en&format=jsonp&jsonp=?";
$("#refreshButton").on("click", function() {
$.getJSON(url, function(json) {
var jsonQuote = json.quoteText;
var jsonAuthor = json.quoteAuthor;
$(".counter").html(jsonAuthor);
$("#authorButton").text("Click to Reveal");
if (jsonAuthor === "") {
$("#refreshButton").trigger("click");
} else {
$(".message").html(jsonQuote);
$("#authorButton").click(function() {
$(this).text(function(i, text) {
return text === "Click to Reveal"
? "- " + jsonAuthor
: "Click to Reveal";
});
});
} //else close
}); //getJSON close
}); //refreshButton Close
});
最佳答案
这里的问题是每次单击刷新按钮时您都在重新绑定(bind)单击函数。这意味着当点击第二个引用时,相同的有效函数被调用两次。如果您在 #authorButton
点击处理程序中添加一条日志消息,您就可以看到这一点。
$("#authorButton").click(function() {
$(this).text(function(i, text) {
console.log(text)
return text === "Click to Reveal" ? "- " + jsonAuthor : "Click to Reveal";
});
});
更好的选择是拥有一个隐藏元素,您可以在获取 json 提要时使用 jsonAuthor
对其进行更新。然后有一个 #authorButton
单击处理程序,它在调用时显示隐藏的元素。
关于javascript - 为什么我的 AuthorButton 的 .on ("click") 函数每隔一个引用只返回我的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290350/