如何通过data-attribute或text设置dropdown select?

How to set dropdown select through data-attribute or text?

我正在开发一个 JavaScript 函数,该函数应该将送货地址表单值复制到帐单地址表单部分,以防两者相同。

我想依靠数据属性、文本或 innerHTML 来设置 select,因为一旦创建了 selection,选项 ID 就会改变。

<select id="order_bill_to_land" name="order[bill_to_land_id]"><option value="">select a country</option>
  <option value="1" data-land="1">Afghanistan</option>
  <option value="2" data-land="2">Aland Islands</option>
  <option value="3" data-land="3">Albania</option>

我的JavaScript函数是:

let land = document.querySelector("#country").getAttribute('data-country');
let bl = document.querySelector("#order_bill_to_land");

for (let i = 0; i < bl.options.length; i++) {
  if (bl.options[i].text === land) {
    return console.log("if loop working");
    bl.selectedIndex = i;
    break;
  };
}

这会产生 0,因为 if 条件不起作用,我从无法登录到控制台的事实中推断出这一点。

为什么会这样?

我找到了 selecting selectedIndex 的较短版本:

bl.selectedIndex = [...bl.options].findIndex (option => option.innerHTML === land);

但它产生 -1。由于它浓缩得很好,我无法找出它不起作用的原因。

我怎样才能让它工作?

提前致谢!

更新

for 循环有效,因为我能够通过在 if 语句外放置 console.log 来记录 bl 的所有选项。 这就是我所做的:

for (let i = 0; i < bl.options.length; i++) {
  console.log(land);                            // Line 185
  console.log(bl.options[i].text);              // Line 186
  if (bl.options[i].text === land) {            // Line 187
    bl.selectedIndex = i;
    break;
  };
}

console.log(bl.selectedIndex);                  // Line 203

产生以下控制台输出:

...
[Log] Germany (dev.js, line 185)
[Log] Zambia (dev.js, line 186)
[Log] Germany (dev.js, line 185)
[Log] Zimbabwe (dev.js, line 186)
[Log] 0 (dev.js, line 203)

在调试中,我可以检查第 187 行的 bloptions[i]land,但不能检查 .text。我不知道这是否正常。因为我能够在 if 语句之外记录它们,所以这应该有效,或者?

理论上它应该循环遍历 bl 并且当 bl.options[i].text (或 .innerHTML)匹配 land 打破循环并输出 bl.selectedIndex = i 并因此设置select表格。

更新 2

在控制台中我得到:

let bl = document.querySelector("#order_bill_to_land")
undefined
let land = document.querySelector("#country").getAttribute('data-country');
undefined
land;
"Germany"
bl.options[84].text
"Germany"

所以都是String类型,但是我测试的时候:

land === bl.options[84].text;

我得到 false.

我怀疑 landbl.options[i].text 最终成为不同的对象类型并跟随 developer.mozilla.org on "Using the equality operators"。这会生成运行时错误。我还不知道怎么解决。

感谢@aseferov 我发现了问题:

land 有一个由 ruby 在服务器上通过以下方式生成的尾部不可见字符:

data-country="<%= @order.land.name %>"

产生了

let land = document.querySelector("#country").getAttribute('data-country');

在 land.trim() 之后条件有效。