【问题标题】:innerHTML (or other method): append li to ul, with <input/> including attributesinnerHTML(或其他方法):将 li 附加到 ul,其中 <input/> 包括属性
【发布时间】:2016-07-31 15:47:56
【问题描述】:

document.getElementById('addplace').addEventListener('click', function() {
    addplace();
  });

function addplace() {
  var node = document.createElement("li"); // Create a <li> node
  node.innerHTML = "<input/>"               
  document.getElementById("waypoints").appendChild(node);
}
<ul id="waypoints"></ul>
<input type="submit" id="addplace" />        
        

上面的sn -p在点击按钮的时候成功给ul添加了一个输入域。但是,当我向输入字段添加属性时,提交按钮不再起作用。

    document.getElementById('addplace').addEventListener('click', function() {
        addplace();
      });

    function addplace() {
      var node = document.createElement("li"); // Create a <li> node
      node.innerHTML = "<input class="field" placeholder="Where to begin?" onFocus="geolocate()" type="text" />"               
      document.getElementById("waypoints").appendChild(node);
    }
    <ul id="waypoints"></ul>
    <input type="submit" id="addplace" />        

谢谢。

【问题讨论】:

    标签: javascript html input innerhtml appendchild


    【解决方案1】:

    您必须转义("\"")字符串中的双引号或使用单引号("'")代替双引号来解决您的问题。

    function addplace() {
      var node = document.createElement("li"); // Create a <li> node
      node.innerHTML = "<input class='field' placeholder='Where to begin?' onFocus='geolocate()' type='text' />"               
      document.getElementById("waypoints").appendChild(node);
    }
    

    转义双引号的解决方案,

    node.innerHTML = "<input class=\"field\" placeholder=\"Where to begin?\" onFocus=\"geolocate()\" type=\"text\" />"               
    

    【讨论】:

      猜你喜欢
      • 2012-08-15
      • 2022-12-05
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      相关资源
      最近更新 更多