我基本上是 javascript 的新手。当用户选择他想查看的书籍和章节并按下提交按钮时,我想从同一页面上的选择表单中填充我网页中的一个 div。这里的代码:
<script type="text/javascript" charset="utf-8">
var setArray = newArray(
bk1, 001, "this is my chapter content for the <div>",
bk1, 002, "this is my chapter content for the <div>",
bk1, 003, "this is my chapter content for the <div>",
bk2, 001, "this is my chapter content for the <div>",
bk2, 002, "this is my chapter content for the <div>"
etc....
);
</script>
<form>
<select id="book">
<option value="">Select Book</option>
<option value="bk1">Book 1</option>
<option value="bk2">Book 2</option>
<option value="bk3">Book 3</option>
</select>
<select id="chapter">
<option value="">Select Chapter</option>
<option value="001">1</option>
<option value="002">2</option>
<option value="003">3</option>
</select>
<button id="button" type="submit">View</button>
</form>
<div id="content">
I want the content from the js array for the selected book and chapter to be placed here without reloading the page.
</div>
注意:我已经简化了代码,使其更容易理解。我确定我的 js 数组不正确,需要根据我的目的进行修复。另外,我不希望页面刷新,只希望更新 div。感谢您的帮助。
最佳答案
正如所建议的那样,您应该认真考虑使用 ajax 来检索此数据,它不会使页面刷新,并允许您将此数据保持半私有(private)状态,并且更易于在后端进行管理。
如果/当您使用 ajax 执行此操作时,您仍然需要类似以下内容:
var booksData = {
book1: [
"chapter 1 content",
"chapter 2 content",
"..."
],
book2: [
"chapter 1 content",
"chapter 2 content",
"..."
]
}
function whenButtonClicked() {
var book = "book1" // get the actual book name from the select input
var chapter = 0 // get the selectedIndex of chapter input
var content = booksData[book][chapter];
var div = document.getElementById("content");
div.innerHTML = content;
}
然后在按钮上使用 onclick 处理程序。有点像
<button id="button" onclick="whenButtonClicked()">
我建议查看像 jQuery 这样的库,它可以让生活更轻松,并且可以清理很多东西。
关于javascript - 以html形式从js数组动态填充div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9990426/