javascript - 以html形式从js数组动态填充div

标签 javascript arrays forms html

我基本上是 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/

相关文章:

javascript - 使用 SWFObject 复杂的 FlashVar 对象?

javascript - "string!"是什么意思?

javascript - Date.UTC() 未返回预期结果

ios - 将多维字符串数组转换为 double

jQuery 将输入类型=文本更改为文本区域

javascript - 如何使用 NodeJS 从 html 表单执行 PATCH 请求?

javascript - 对我生成的每个索引创建不同的 V-MODEL

javascript - 如何根据表单字段类型自动更新价格="number"

java - 如何在Java中将for循环输出分离到数组中?

php - 如何在 SELECT 子句中使用多个 WHERE 表达式?