首页 > 解决方案 > getAttribute 未设置

问题描述

我需要根据第一个框的选择来同步这两个下拉框。

我不能"value"为此使用标签,因为代码库从其他地方提取这些值。

以下代码不起作用:

html

<select name="alpha">
  <option id="1" data-sync="1">One</option>
  <option id="2" data-sync="2" selected>Two</option>
  <option id="3" data-sync="3">Three</option>
  <option id="4" data-sync="1">Four One</option>
  <option id="5" data-sync="2">Five Two</option>
</select>
<select name="beta">
  <option value="1" id="1" name="1" syncOne="1">2</option>
  <option value="2" name="2"  id="2" syncOne="2">4</option>
  <option value="3" name="3" id="3" syncOne="3">6</option>
</select>

JavaScript

window.onload = function()
{
    document.getElementsByName("alpha")[0].onchange = function()
    {
        document.getElementsByName("beta")[0].getAttribute("syncOne") = this.options[this.selectedIndex].getAttribute("data-sync"); 
    }

    // Trigger when loading.
    document.getElementsByName("alpha")[0].onchange();
}

但是,下一个代码更改有效,但超出了项目规范(我不能使用value属性)。

document.getElementsByName("beta")[0].value = this.options[this.selectedIndex].getAttribute("data-sync");

有什么建议么?

标签: javascripthtml

解决方案


首先,请注意这syncOne不是 的属性<select name="beta">,而是与该选择器相关的每个选项上可用的属性,因此下一个代码不会产生您所期望的结果:

document.getElementsByName("beta")[0].getAttribute("syncOne") = ...;

现在,一种解决方案是使用querySelector()从选择器中获取相关option元素beta,然后设置该selected选项的属性:

例子:

window.onload = function()
{
  document.getElementsByName("alpha")[0].onchange = function()
  {
    let sel = this.options[this.selectedIndex].getAttribute("data-sync");
    let betaOpt = document.querySelector(`select[name="beta"] option[syncOne="${sel}"]`);
    betaOpt.selected = true;
  }

  // Trigger when loading.
  document.getElementsByName("alpha")[0].onchange();
}
<select name="alpha">
  <option id="1" data-sync="1">One</option>
  <option id="2" data-sync="2" selected>Two</option>
  <option id="3" data-sync="3">Three</option>
  <option id="4" data-sync="1">Four One</option>
  <option id="5" data-sync="2">Five Two</option>
</select>
<select name="beta">
  <option value="1" id="1" name="1" syncOne="1">2</option>
  <option value="2" name="2" id="2" syncOne="2">4</option>
  <option value="3" name="3" id="3" syncOne="3">6</option>
</select>

请注意,我使用模板文字ES6功能)来生成querySelector(). 如果您不能使用它,您可以使用字符串连接,如下所示:

let betaOpt = document.querySelector('select[name="beta"] option[syncOne="' + sel + '"]');

推荐阅读