我在jQuery中定义了一个数组,我想从中随机选择一个项目并在网站上显示它,但也可以选择推特这个确切的项目。看看我在<script> ... </script>
元素中定义的代码。
$(document).ready(function() {
$("#click").click(function() {
var quotPick = quotes[Math.floor(Math.random()*quotes.length)];
$("#text").text(quotPick);
});
$("#tweet").click(function() {
var quotPick = quotes[Math.floor(Math.random()*quotes.length)];
window.open('https://twitter.com/intent/tweet?hashtags= cali, hank&text=' + quotPick);
});
});
如果我像这样编写代码,quotPick
变量将始终以不同的方式显示。如果我在$(#click)...
之外或$(document).ready ...
之前定义它,我只能点击按钮一次以生成项目选择。
我在哪里或如何定义quotPick
以便我的代码有效?我在哪里做出错误的假设?先谢谢你,伙计们!
P.S。我也尝试了按钮的onclick()
功能,但也没有找到令人满意的解决方案。
答案 0 :(得分:1)
可以尝试类似:
$(document).ready(function() {
var quotPick;
$("#click").click(function() {
quotPick = quotes[Math.floor(Math.random()*quotes.length)];
$("#text").text(quotPick);
});
$("#tweet").click(function() {
window.open('https://twitter.com/intent/tweet?hashtags= cali, hank&text=' + quotPick);
});
});
答案 1 :(得分:1)
你可以试试这个。
<script>
var quotPick; //Define it in the beginning of script. This will help you in using the same variable globally
<!--Other Code here can also use the same value-->
$(document).ready(function() {
$("#click").click(function() {
quotPick = quotes[Math.floor(Math.random()*quotes.length)];
$("#text").text(quotPick);
});
$("#tweet").click(function() {
window.open('https://twitter.com/intent/tweet?hashtags= cali, hank&text=' + quotPick);
});
});
</script>
这应该对你有用
答案 2 :(得分:0)
let quotes = ["ds","sd"]
let quotPick;
$(document).ready(function() {
$("#click").click(function() {
quotPick = quotes[Math.floor(Math.random()*quotes.length)];
$("#text").text(quotPick);
});
$("#tweet").click(function() {
window.open('https://twitter.com/intent/tweet?hashtags= cali, hank&text=' + quotPick);
});
});