当我单击链接时,我的 jQuery 代码就会运行。但是,如果我多次单击该链接,该代码将重复自身并出现在之前的代码下方,这是我不希望它这样做的。 另外,如果我单击“关闭”选项并重新打开它,它将会重复。我该如何阻止它这样做?顺便说一下,这是代码:
$("#pop").click(function() {
$("#overlay_form").fadeIn(1000);
$("#statsStr").append('<br />' + strOne).fadeIn(1000);
$("#statsCun").append('<br />' + cunOne).fadeIn(1000);
$("#statsAgil").append('<br />' + agilOne).fadeIn(1000);
$("#statsWis").append('<br />' + wisOne).fadeIn(1000);
});
$("#close").click(function(){
$("#overlay_form").fadeOut("slow");
$("#statsStr").fadeOut("slow");
$("#statsCun").fadeOut("slow");
$("#statsAgil").fadeOut("slow");
$("#statsWis").fadeOut("slow");
});
感谢您的帮助!
编辑:我已采纳建议将我的代码更改为:
// append the strings only once on load
$(function() {
$("#statsStr").append('<br />' + strOne);
$("#statsCun").append('<br />' + cunOne);
$("#statsAgil").append('<br />' + agilOne);
$("#statsWis").append('<br />' + wisOne);
});
$("#pop").click(function() {
$("#overlay_form, #statsStr, #statsCun, #statsAgil, #statsWis").fadeIn(1000);
});
$("#close").click(function(){
$("#overlay_form, #statsStr, #statsCun, #statsAgil, #statsWis").fadeOut("slow");
});
虽然效果很好,但有一个问题。我正在制作的游戏需要“#pop”功能每隔一段时间更新一次以显示您的“统计数据”。有没有办法刷新代码以便显示更新后的变量?
最佳答案
编辑尝试以下解决方案:
//call this method whenever you want to update your stats
//passing in the variables
var updateStats = function(str, cun, agil, wis) {
$("#statsStr").html('<br />' + str);
$("#statsCun").html('<br />' + cun);
$("#statsAgil").html('<br />' + agil);
$("#statsWis").html('<br />' + wis);
};
$("#pop").click(function() {
$("#overlay_form, #statsStr, #statsCun, #statsAgil, #statsWis").fadeIn(1000);
});
$("#close").click(function(){
$("#overlay_form, #statsStr, #statsCun, #statsAgil, #statsWis").fadeOut("slow");
});
$(document).ready(function() {
// assuming you have set these variables in the current scope.
updateStats(strOne, cunOne, agilOne, wisOne);
});
关于javascript - 如何阻止 jQuery 页面元素重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588624/