英文:
How do I cleanly update a large element's content in HTML?
问题
我正在开发一个网站,允许用户通过生成器的多个阶段,我希望将这个过程放在一个HTML页面上进行。我目前尝试的方法是通过更新一个div的innerHTML来实现,但这样会变得非常冗长和复杂。是否有一种方法可以将内容编写在单独的HTML文件中,然后在调用JavaScript函数时导入它并更新元素?
function stepTwo() {
document.getElementById("mainText").innerHTML = `
<h3>第二个问题</h3>
<select id="gender">
<option value="male">男性</option><option value="female">女性</option>
<option value="non-binary">非二元</option>...
</select>
<a 大量更多的行>
`
}
显然,这样的代码看起来很不优雅。我正在寻找任何一种方法来简化它,无论是通过导入另一个HTML文件还是其他方式。感谢您的帮助!
英文:
I'm working on a website that lets the user go through several stages of a generator, and I want to do it on one HTML page. The current way I'm trying to do this is by updating a div's innerHTML, but that gets very long and complicated fast. Is there a way to write the content in a separate HTML file, then import it & update the element when a javascript function is called?
function stepTwo() {
document.getElementById("mainText").innerHTML = `
<h3>Question two</h3>
<select id = "gender">
<option value = "male">Male</option><option value = "female"> Female</option>
<option value = "non-binary">Non-binary</option>...
</select>
<a LOT more lines>
`
}
Obviously this is very ugly. I'm looking for any way to clean it up, be it by importing another HTML file or some other way. Thanks for your help!
答案1
得分: 1
是的,您可以将内容分隔到单独的HTML文件中,并使用JavaScript将它们动态加载到主HTML页面中。
-
为生成器的每个阶段创建单独的HTML文件
-
在您的主HTML文件中,创建一个<div>或任何其他容器元素
-
您可以使用AJAX从单独的HTML文件加载内容,并在调用函数时更新内容容器。
function loadStage(stageNumber) {
$.ajax({
url: 'stage' + stageNumber + '.html', // 替换为正确的文件名
dataType: 'html',
success: function(data) {
$('#contentContainer').html(data);
},
error: function() {
console.log('无法加载第' + stageNumber + '阶段的内容。');
}
});
}
loadStage(1);
这有助于简化您的代码并使其更容易管理生成器的每个阶段的内容。
英文:
Yes, you can separate the content into separate HTML files and dynamically load them into your main HTML page using JavaScript.
-
Create separate HTML files for each stage of the generator
-
In your main HTML file, create a <div> or any other container element
-
you can use AJAX to load the content from the separate HTML files and update the content container when a function is called.
function loadStage(stageNumber) {
$.ajax({
url: 'stage' + stageNumber + '.html', // Replace with the correct file name
dataType: 'html',
success: function(data) {
$('#contentContainer').html(data);
},
error: function() {
console.log('Failed to load stage ' + stageNumber + ' content.');
}
});
}
loadStage(1);
This helps simplify your code and makes it easier to manage the content for each stage of your generator
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论