2

我想在显示文本与实际值不同的下拉菜单中进行选择。做出选择后,我希望 SELECT 框中显示的实际 HTML 显示实际值,而不是所选文本。

到目前为止我有这个。它几乎可以工作,但是一旦我做出选择,它确实将可视字段设置为该值,但是如果我再次单击下拉菜单,则初始可选选项不再存在,只有值。

<select size="1" style="width: 28mm; border: 1px solid;"" name="Priority"
        id="Priority" onChange="setDevices(this);">
    <option selected><? print($row[Priority]); ?></option>
    <option value="Pri1">This is Priority 1</option>
    <option value="Pri2">This is Priority 2</option>
    <option value="Pri3">This is Priority 3</option>
    <option value="Pri4">This is Priority 4</option>
</select>

function setDevices(elem) {
    elem.options[elem.selectedIndex].innerHTML = elem.options[elem.selectedIndex].value
}
4

2 回答 2

1

将其提前到 2019 年,我们现在可以使用数据属性来存储以前的信息

function setDevices(elem) {
  let arrMeta = elem.dataset.meta.split("|");
  let index = parseInt(arrMeta[0], 10);
  let text = arrMeta[1];

  //Reset the old text
  elem.options[index].innerHTML = text;

  //Set the meta from the new
  elem.dataset.meta = elem.selectedIndex + "|" + elem.options[elem.selectedIndex].innerHTML;

  //Update the new
  elem.options[elem.selectedIndex].innerHTML = elem.value;

}
<select size="1" style="width: 28mm; border: 1px solid;" name="Priority" id="Priority" onchange="setDevices(this);" data-meta="0|">
  <option selected>
    <? print($row[Priority]); ?>
  </option>
  <option value="Pri1">This is Priority 1</option>
  <option value="Pri2">This is Priority 2</option>
  <option value="Pri3">This is Priority 3</option>
  <option value="Pri4">This is Priority 4</option>
</select>

您当然可以使用 2 个数据属性,一个用于上一个选定的索引,一个用于上一个文本。

于 2019-10-23T00:24:43.483 回答
0

2014 年 2 月 2 日编辑

所以你想让“This is Priority 1”在选中时更改为“Pri1”,在未选中时更改回来?

第一次更改原始值时,您需要将原始值存储在某处,并添加一些代码以在选择更改时恢复该存储值。

您可以使用“rel”属性:

<select size="1" style="width: 28mm; border: 1px solid;"" name="Priority" id="Priority" onchange="setDevices(this);">
  <option selected><? print($row[Priority]); ?></option>
  <option value="Pri1" rel="This is Priority 1">This is Priority 1</option>
  <option value="Pri2" rel="This is Priority 2">This is Priority 2</option>
  <option value="Pri3" rel="This is Priority 3">This is Priority 3</option>
  <option value="Pri4" rel="This is Priority 4">This is Priority 4</option>
</select>

<script>
  function setDevices(elem){
    for(i=0; i<elem.options.length; i++) {
      elem.options[i].innerHTML = (i == elem.selectedIndex) ? elem.options[i].value : elem.options[i].getAttribute("rel");
    }
  }
</script>
于 2013-11-14T13:40:23.160 回答