繁体   English   中英

下拉列表中的附加属性 (Javascript)

[英]Additional attributes in a dropdown (Javascript)

我正在通过调用函数来填充下拉列表

    function createOption(dropdown, text, value, gid) {
      var x = document.createElement('option');
      x.value = value;
      x.text = text;
      x.setAttribute("gid",gid);
      dropdown.options.add(x);
    }

我希望下拉菜单有一个附加属性“id”,以便在 id 的特定值处弹出一个警告框。 现在我调用另一个函数来弹出警告框。

function showPopUp(dropdown) {
  console.log("from Show Pop-up: " + dropdown.getAttribute("gid")); //PRINTS null
  if(dropdown.getAttribute("gid")==5){
        alert("Approval needed");
    }
}

我无法在另一个函数中访问下拉列表的 id 值。

您可以在 javascript 中使用Element.setAttribute()来完成。 它设置指定元素上的属性值。 如果属性已经存在,则更新值; 否则,将添加具有指定名称和值的新属性。

 <select id="mySelect"> </select> <p>Click the button to create an OPTION element with an id.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x = document.createElement("OPTION"); x.value = "value"; x.text = "text"; x.setAttribute("data-id", "id"); document.getElementById("mySelect").appendChild(x); } </script>

PS您也可以根据值区分特定选项。 不需要使用id。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM