Javascript Can';t在jQuery函数中分配变量
因此,我有一个按钮,它应该在运行函数时生成一个变量“quote”。然后我们使用jQuery在页面上显示引号,但是每当我尝试分配变量时,jQuery函数就停在那里,什么也没有发生。我不知道发生了什么事。这是按钮代码和javascript。非常感谢Javascript Can';t在jQuery函数中分配变量,javascript,jquery,Javascript,Jquery,因此,我有一个按钮,它应该在运行函数时生成一个变量“quote”。然后我们使用jQuery在页面上显示引号,但是每当我尝试分配变量时,jQuery函数就停在那里,什么也没有发生。我不知道发生了什么事。这是按钮代码和javascript。非常感谢 <button class="btn btn-primary" id="quoteBtn">new quote</button> var quote = quote(); function quote() { var n
<button class="btn btn-primary" id="quoteBtn">new quote</button>
var quote = quote();
function quote() {
var num = randomRange(1, 3);
switch (num) {
case 1:
return ["hat.", "- hatboy"];
case 2:
return ["shoes.", "- shoeboy"];
case 3:
return ["belt.", "- beltboy"];
}
}
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$(document).ready(function() {
$("#quoteBtn").on("click", function() {
var quote = quote();
$("h2").html("<i class=\"fa fa-quote-left fa-lg\"></i>" + " " + quote[0]);
$("#author").html(quote[1]);
});
$("h2").html("<i class=\"fa fa-quote-left fa-lg\"></i>" + " " + quote[0]);
$("#author").html(quote[1]);
});
新报价
var quote=quote();
函数引号(){
var num=随机范围(1,3);
开关(num){
案例1:
return[“hat.”、“-hatboy”];
案例2:
返回[“鞋子”,“-鞋盒”];
案例3:
返回[“皮带”,“皮带组件”];
}
}
函数随机范围(最小值、最大值){
返回Math.floor(Math.random()*(max-min+1))+min;
}
$(文档).ready(函数(){
$(“#quoteBtn”)。在(“单击”,函数(){
var quote=quote();
$(“h2”).html(“+”+引号[0]);
$(“#作者”).html(引用[1]);
});
$(“h2”).html(“+”+引号[0]);
$(“#作者”).html(引用[1]);
});
您有一个变量和一个同名函数。您应该将函数命名为不同的名称,这样它们就不会发生冲突(例如,getQuote()
):
var quote=getQuote();
函数getQuote(){
var num=随机范围(1,3);
开关(num){
案例1:
return[“hat.”、“-hatboy”];
案例2:
返回[“鞋子”,“-鞋盒”];
案例3:
返回[“皮带”,“皮带组件”];
}
}
函数随机范围(最小值、最大值){
返回Math.floor(Math.random()*(max-min+1))+min;
}
$(文档).ready(函数(){
$(“#quoteBtn”)。在(“单击”,函数(){
var quote=getQuote();
$(“h2”).html(“+”+引号[0]);
$(“#作者”).html(引用[1]);
});
$(“h2”).html(“+”+引号[0]);
$(“#作者”).html(引用[1]);
});代码>
引用
您有一个变量和一个同名函数。您应该将函数命名为不同的名称,这样它们就不会发生冲突(例如,getQuote()
):
var quote=getQuote();
函数getQuote(){
var num=随机范围(1,3);
开关(num){
案例1:
return[“hat.”、“-hatboy”];
案例2:
返回[“鞋子”,“-鞋盒”];
案例3:
返回[“皮带”,“皮带组件”];
}
}
函数随机范围(最小值、最大值){
返回Math.floor(Math.random()*(max-min+1))+min;
}
$(文档).ready(函数(){
$(“#quoteBtn”)。在(“单击”,函数(){
var quote=getQuote();
$(“h2”).html(“+”+引号[0]);
$(“#作者”).html(引用[1]);
});
$(“h2”).html(“+”+引号[0]);
$(“#作者”).html(引用[1]);
});代码>
引用
代码笔的链接如何?或者至少在堆栈上创建溢出…也许您的变量var quote
应该有不同的名称。我想它可能会覆盖你的函数引号
。到代码笔的链接如何?或者至少在堆栈上创建溢出…也许您的变量var quote
应该有不同的名称。我想它可能会覆盖您的函数引号
。