【问题标题】:createTextNode surrounding my select list in unwanted quotation markscreateTextNode 用不需要的引号括住我的选择列表
【发布时间】:2023-03-31 14:00:02
【问题描述】:

我想使用按钮将选择列表添加到我的网站。 我需要使用节点,因为我需要能够在 DOM 中访问它,以便稍后检索它的值,因此我不能使用 innerHTML。

我的问题是 createTextNode 似乎用引号将我的列表括起来,因此它不会显示。谁能帮帮我

<!doctype html>
<html>
 <head>
  <title> Pop Up </title>

<script>
function change()
{
    var theDiv = document.getElementById("dropDownList");
    var content = document.createTextNode("<select name='scrapbookID' id='scrapbookID'><option value='15'>one</option><option value='18'>two</option><option value='20'>three</option><option value='21'>four</option></select>");

    theDiv.appendChild(content);
}
</script>

<style type = "text/css">


</style>


</head>
<body>

    <div id = "signout">
        Your are Currently signed in.<br />
        <a href = "#" id = "signOutPHP">Sign Out</a>
         <div id = "dropDownList">
            <button onclick="change()">Add List</button>

        </div>
    </div>

</body>

【问题讨论】:

    标签: javascript html ajax web-applications


    【解决方案1】:

    您需要的是.createElement() 它创建一个给定的元素,而createTextNode 创建具有给定内容的文本节点。

    function change()
    {
        var theDiv = document.getElementById("dropDownList");
    
        var select  = document.createElement('select');
        select.name = 'scrapbookID';
        select.id = 'scrapbookID';
        select.innerHTML = "<option value='15'>one</option><option value='18'>two</option><option value='20'>three</option><option value='21'>four</option>"
    
        theDiv.appendChild(select);
    }
    

    演示:Fiddle

    【讨论】:

      【解决方案2】:

      当您创建一个文本节点时,它会被完全视为:文本,而不是 HTML。但是正确构建 DOM 会更干净!

      function change() {
          var theDiv = document.getElementById("dropDownList");
      
          var selectBox = document.createElement("select");
          selectBox.id = "scrapbookID";
          selectBox.name = "scrapbookID";
      
          var options = {
              "15": "one",
              "18": "two",
              "20": "three",
              "21": "four"
          };
      
          for(var x in options) {
              if(options.hasOwnProperty(x)) {
                  var option = document.createElement("option");
                  option.value = x;
                  option.appendChild(document.createTextNode(options[x]));
      
                  selectBox.appendChild(option);
              }
          }
      
          theDiv.appendChild(selectBox);
      }
      

      【讨论】:

        猜你喜欢
        • 2013-07-28
        • 1970-01-01
        • 2016-01-29
        • 2010-09-09
        • 1970-01-01
        • 2013-06-16
        • 2014-08-09
        • 1970-01-01
        • 2020-10-20
        相关资源
        最近更新 更多