javascript - Html <select> selected 属性在 jQuery 中无法正常工作

标签 javascript html select

我正在尝试在选择中列出一些 amChart 图表。它没有任何默认图表,因此我尝试为 <select> 设置默认值通过对其中一个选项使用 selected 属性,它会在选择框中被选中,但不会出现在页面上。

    var currentChart;
    function showChart( divid ) {
    
      if (currentChart !== undefined)
        currentChart.style.display = "none";
      if ( divid ) {
        currentChart = document.getElementById(divid);
        currentChart.style.display = "block";
      }
      else {
        currentChart = undefined;
      }
    }
    <select onchange="showChart(this.options[this.selectedIndex].value);">
      <option value="">Select the chart to show</option>
      <option value="chart1" selected>Chart #1</option>
      <option value="chart2">Chart #2</option>
      <option value="chart3">Chart #3</option>
    </select>
    
    <div id="chart1" class="chartBoxSingle" style="display: none;">Chart 1</div>
    <div id="chart2" class="chartBoxSingle" style="display: none;">Chart 2</div>
    <div id="chart3" class="chartBoxSingle" style="display: none;">Chart 3</div>

最佳答案

您只能对标签使用 onload 事件

 <body>, <frame>, <iframe>, <img>, <input type="image">, <link>,
 <script>, <style>

对于其他元素,您可以通过两种方式执行

  1. 在元素后面插入包含要在元素加载时执行的函数的脚本标记或

  2. 使用jquery

$(document).ready(function() { showChart('chart1'); });

<script>
  var currentChart;

  function showChart(divid) {
    if (currentChart !== undefined)
      currentChart.style.display = "none";
    if (divid) {
      currentChart = document.getElementById(divid);
      currentChart.style.display = "block";
    } else {
      currentChart = undefined;
    }
  }
</script>
<select onchange="showChart(this.options[this.selectedIndex].value);">
      <option value="">Select the chart to show</option>
      <option value="chart1" selected>Chart #1</option>
      <option value="chart2">Chart #2</option>
      <option value="chart3">Chart #3</option>
    </select>

<div id="chart1" class="chartBoxSingle" style="display: none;">char1</div>
<div id="chart2" class="chartBoxSingle" style="display: none;">char2</div>
<div id="chart3" class="chartBoxSingle" style="display: none;">char3</div>
<script type="text/javascript">
  showChart('chart1');
</script>

关于javascript - Html <select> selected 属性在 jQuery 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49108207/

相关文章:

mysql - 如何将 UNION 与两个选择和一些 JOINS 一起使用

javascript - 使用 Meteor 在 Mongo 中搜索多个属性

html - 如何在将元素保留在页面上的同时使用 css 隐藏它?

javascript - 无法使用 Angular 和 Spring 触发有效请求

python - 使用 python requests 库网站总是挂起

javascript - 使用 href 值查找 anchor 标记并使用新的 href 值更改 href 值

MySQL - 如何选择没有特定数据的查询值

javascript - 在 Javascript 中,如何将新选项添加​​到 Html Select 中,根据文本的字母顺序值插入

javascript - Phantomjs javascript继承误区

javascript - javascript 中的意外标识符错误