gpt4 book ai didi

javascript - 使用 jQuery 创建 HTML 元素并不总是有效

转载 作者:行者123 更新时间:2023-12-01 01:49:40 25 4
gpt4 key购买 nike

我正在为我们的一个项目构建一个实时主题选择器,并且它有效。那太棒了!但我还剩下一个错误,我无法解决它,这让我发疯。

这就是问题所在:在加载主题选择器页面时,主干应用程序(它是使用 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 会创建样式表。所以只有在初始化时它才不起作用,这让我发疯。

希望有人能向我解释为什么每次都会调用完全相同的函数,但在初始化时它会比主题更改时有其他输出(具有相同的数字和变量)。

最佳答案

整个问题是:我在初始化 iFrame 之前就调用了 selectColorset()。感谢@Leandro,我发现这是我的错误。谢谢您的帮助!

关于javascript - 使用 jQuery 创建 HTML 元素并不总是有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13624378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com