【问题标题】:Javascript - get attribute of dropbox menuJavascript - 获取下拉菜单的属性
【发布时间】:2017-09-23 21:39:54
【问题描述】:

我有这个 HTML 代码:

<select id="ITAAServerList" name="ITAAServerList" style="visibility:visible">
     <option ServerName="SERVER01" IPAddress="192.168.46.1" StartPageName="SERVER01_Start.html">SERVER01</option>
     <option ServerName="SERVER02" IPAddress="192.168.46.2" StartPageName="SERVER02_Start.html">SERVER02</option>
     <option ServerName="SERVER03" IPAddress="192.168.46.3" StartPageName="SERVER03_Start.html">SERVER02</option>
</select>
<button type="submit" name="oNext" id="oNext" onclick ="OnClickNext()" class="item cursor-pointer login-button">LOGIN</button>
...
<script type="text/javascript" src="onclicknext.js"></script>

还有这个 JS 代码:

function OnClickNext() {
    var oITAAServer = document.getElementById('ITAAServerList').options[this.selectedIndex].getAttribute('StartPageName');  
    alert(oITAAServer);
};

我无法从下拉菜单中获取 StartPageName 属性。帮忙?

【问题讨论】:

  • 刚刚更新了JS代码。

标签: javascript html drop-down-menu options


【解决方案1】:

你快到了 - 你只需要对 &lt;select&gt; 元素而不是 this 执行 .selectedIndex

function OnClickNext() {
    var selectElement = document.getElementById('ITAAServerList');    
    var selectedOption = selectElement.options[ selectElement.selectedIndex ];  //not this.selectedIndex   
    var oITAAServer = selectedOption.getAttribute('StartPageName');  
    alert(oITAAServer);
};
<select id="ITAAServerList" name="ITAAServerList" style="visibility:visible">
     <option ServerName="SERVER01" IPAddress="192.168.46.1" StartPageName="SERVER01_Start.html">SERVER01</option>
     <option ServerName="SERVER02" IPAddress="192.168.46.2" StartPageName="SERVER02_Start.html">SERVER02</option>
     <option ServerName="SERVER03" IPAddress="192.168.46.3" StartPageName="SERVER03_Start.html">SERVER03</option>
</select>
<button type="submit" name="oNext" id="oNext" onclick ="OnClickNext()" class="item cursor-pointer login-button">LOGIN</button>

【讨论】:

  • 这样可以,但我建议避免做很多事情的非常长的行 - 使代码更难维护和管理。
  • 对不起,我在这里太新了 :) 我删除了长代码:var oITAAServer =document.getElementById('ITAAServerList').options[document.getElementById('ITAAServerList').selectedIndex].getAttribute('StartPageName'); 将使用你的代替!仅供参考。
猜你喜欢
  • 1970-01-01
  • 2020-11-28
  • 2017-11-14
  • 2019-10-31
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
相关资源
最近更新 更多