我正在为我们的项目构建一个活动的主题选择器,它可以工作。那很棒!但是我还有一个缺陷,我无法解决,这让我疯狂。使用jQuery创建HTML元素并不总是有效
这就是问题:在你加载主题选择器页面的时候,骨干应用程序(它是用Backbone JS,Underscore JS和jQuery构建的)启动。在初始化时,应用程序查找几件事情,其中一件事是:我需要为当前主题使用哪种颜色集(当前主题设置存储在数据库中)。
这是被称为在初始化函数:
// Select the colorset for the first time a new theme is picked
selectColorset: function(newTheme) {
// Check or this is a new theme or not
var themeCheck = (typeof newTheme !== "undefined") ? true : false,
colorset = (!themeCheck) ? parseInt($("#js-colorset-input").val() , 10) : 0;
// Select the right list
$("#js-theme-colors ul").eq(colorset).addClass("selected-set");
this.renderColorStyle(colorset);
}
正如你可以看到这个功能用在两个方面:一是在初始化,当你切换到其他主题。
首先我查找:为什么要调用这个函数?它是在更改事件上调用还是在初始化时调用?如果它在初始化时被调用,newTheme变量将不会保存任何数据。
初始化时,颜色集编号将成为页面隐藏字段中的数字。所以,现在我们已经得到了色定数,我们可以使颜色设置样式表(this.renderColorStyle(colorset)):
// Insert the color stylesheet
renderColorStyle: function(colorset) {
// Check or the colorset is given
if(typeof colorset === "undefined" || colorset === "") {
colorset = 0;
}
// Define the stylesheet for this theme
if($("#js-theme-iframe").contents().find("#js-theme-colorset").length > 0) {
// Change the current stylesheet
$("#js-theme-iframe")
.contents()
.find("head #js-theme-colorset")
.attr("href", "stylesheets/themes/theme-" + this.themeID + "/theme-color-" + colorset + ".css");
} else {
// Insert a new stylesheet
var stylesheet = $("<link />", {
href: "stylesheets/themes/theme-" + this.themeID + "/theme-color-" + colorset + ".css",
rel: "stylesheet",
id: "js-theme-colorset"
});
// Append the stylesheet to the iframe
$("#js-theme-iframe").contents().find("head").append(stylesheet);
}
}
正如你所看到的,我第一次检查,或者我们已经有了一个颜色集(只是可以肯定的),因为我们没有初始化的颜色集样式表,我们将构建一个。这是用jQuery完成的。正如你所看到的,我使用href,rel和id(用于查找颜色集样式表)构建元素。
但jQuery不断给我一个空的数组返回初始化..所以样式表不存在..所有的数据都在那里,当我使用console.log()函数来查看或数据真的存在事实证明它是。所以不是这样。
但我真的不明白为什么会发生这种情况。因为如果我在主题变化上调用这些函数,这一切都会起作用,并且jQuery创建样式表..所以只在初始化时它不起作用,并且它使我发疯。
希望有人能解释我如何有可能每次都会调用完全相同的函数,但在初始化时它有另一个输出(具有相同的数字和变量),而不是主题更改。