我正在尝试创建多个 html 链接来用作按钮。我现在正在创建 15 个,将来可能需要添加更多,所以我想通过 JS 来完成。以下代码在屏幕上添加对象,但按钮不执行分配的功能。事实上,他们根本不做任何事情,他们只是转到index.html#。
function buttonCreate(){
var element = $(".left");
for (i in upgrades){
a = $('<a>',{
text: i,
href: '#',
id: i
});
var upgrade_button = $('#' + i);
upgrade_button.click(function(){upgrade(i);return false;});
a.addClass('myButton');
a.appendTo(element);
para = $('<p>',{
text: "",
id: i+"_upgrade"
});
para.appendTo(element);
para2 = $('<p>',{
text: "",
id: i+"_income"
});
para2.appendTo(element);
document.getElementById(i+"_upgrade").innerHTML = "You need " + Math.round(upgrades[i].cost).toLocaleString() + " to upgrade " + i;
document.getElementById(i+"_income").innerHTML = "Next " + i + " give " + Math.round(upgrades[i].income).toLocaleString() + " passive income";
}
}
我还尝试将该函数直接添加到新创建的链接元素中。
编辑:
我给你升级变量和升级函数:
var upgrades = {
'A': {
cost: 100,
income: 10
},
'B': {
cost: 1000,
income: 100
},
'C': {
cost: 10000,
income: 1000
};
函数:
function upgrade(type){
if ((points - upgrades[type].cost) >= 0) {
points -= upgrades[type].cost;
upgrades[type].cost *= upgrade_incr;
pincome += upgrades[type].income;
clearInterval(intervalVar);
intervalVar = setInterval(function(){pas_incr(pincome/8);},125);
//upgrades[type].income *= val_incr;
display = Math.round(points).toLocaleString();
document.getElementById("points").innerHTML = "Points: " + display;
document.getElementById(type+"_upgrade").innerHTML = "You need " + Math.round(upgrades[type].cost).toLocaleString() + " to upgrade " + type;
document.getElementById(type+"_income").innerHTML = "Each " + type +" gives " + Math.round(upgrades[type].income).toLocaleString() + " passive income";
document.getElementById("pincome").innerHTML = "You have " + Math.round(pincome).toLocaleString() + " passive income";
}
}
我同时使用 JS 和 Jquery 的事实是我刚刚学习了 jquery,并开始实现它。需要注意的是,我也无法让它与简单的 JS 一起工作。
最佳答案
您尝试在将按钮插入 DOM 之前查询按钮 (upgrade_button
)。但是您的本地范围内已经有了该按钮 (a
)。只需在创建按钮时添加 click
属性即可。
而不是:
a = $('<a>',{
text: i,
href: '#',
id: i
});
var upgrade_button = $('#' + i);
upgrade_button.click(function(){upgrade(i);return false;});
尝试:
var a = $('<a>',{
text: i,
href: '#',
id: i,
click: function(){upgrade(i);return false;}
});
更新
如TrueBlueAussie在注释中指出,您不能在 click
闭包中使用 i
,因为它将采用您的 for 循环
在该时间点的最终值当实际调用 click
时。
新版本:
var a = $('<a>',{
text: i,
href: '#',
id: i,
click: function(){ upgrade(this.id); return false; }
});
关于javascript - 使用 jQuery 在链接上添加功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27188228/