javascript - 如何使用数组更改 html 元素属性
问题描述
您好我正在尝试让这个脚本工作,但它只是不能正常工作 getquote 函数从定义的 arr 获取报价和随机颜色,然后根据它获得的数据更新页面。调用 getquote 后,没有任何输出按预期工作
任何人都可以帮我告诉我故障来自哪里或指出损坏的部分吗?
var colors = [
'#490A3D',
'#BD1550',
'#E97F02',
'#F8CA00',
'#8A9B0F',
'#69D2E7',
'#FA6900',
'#16a085',
'#27ae60',
'#2c3e50',
'#f39c12',
'#e74c3c',
'#9b59b6',
'#FB6964',
'#342224',
'#472E32',
'#77B1A9',
'#73A857'
];
var quotes = [
["You only live once, but if you do it right, once is enough.", "Mae West"]
]
var currentQuote = "";
var currentAuthor = "";
var randomquote = "";
var randomcolor = "";
function getQuote() {
randomquote = Math.floor(Math.random() * quotes.length);
randomcolor = Math.floor(Math.random() * colors.length);
currentQuote = quotes[randomquote][0];
currentAuthor = quotes[randomquote][1];
$(document).ready(function() {
$('html body').animate({
backgroundColor: colors[randomcolor],
color: colors[randomcolor]
}, 500);
$('#newquote, .social-icons .fa-twitter').animate({
backgroundColor: colors[randomcolor]
}, 500);
$('blockquote footer').animate({
color: colors[randomcolor]
}, 500);
$('blockquote').animate({
borderLeftColor: colors[randomcolor]
}, 500);
$('#quotetext').animate({
opacity: 0
}, 500, function() {
$(this).animate({
opacity: 1
}, 500);
$(this).text(currentQuote);
});
$('#quotesource').animate({
opacity: 0
}, 500, function() {
$(this).animate({
opacity: 1
}, 500);
$(this).text(currentAuthor);
});
});
}
getQuote();
$(document).ready(function() {
$('#newquote').on('click', getQuote());
});
body {background:#16a085;}
.btn-primary {
width: 100px;
height: 40px;
background:#490A3D;
}
<body>
<h2 id="quotetext"></h2>
<footer id="quotesource"></footer>
<button class="btn btn-primary" id="newquote">New Quote</button>
</body>
解决方案
$(document).ready(function() {
$('#newquote').on('click', getQuote);
});
您需要将回调作为变量传递。在您的示例中,它被调用并且函数的结果(什么都没有)被传递给事件侦听器。
推荐阅读
- javascript - 有没有办法在画布上渲染动画透明 gif 并更改帧之间的延迟
- ios - 如何在移动设备上设置 ionic-segment-button 的样式,使其看起来像是在 Chrome 浏览器中呈现的?
- oracle - PLSQL:如何使用变量作为 table_name 创建游标
- jquery - jquery复制到剪贴板
- javafx - 单击按钮2时如何更新按钮1上的计数器
- mockito - 如何对控制器进行junit测试?
- android - 是否可以在 Room 数据库中存储倒数计时器的实例?
- python - OpenCV多帧成视频
- python - 使用 Matlab 中的 tensorflow-gpu 执行 python 时出现 DLL 错误
- makefile - 基于依赖通配符使用makefile生成目标子目录