innerHTML (or other method): append li to ul, with <input/> including attributes

浪子不回头ぞ 提交于 2019-12-25 07:06:15

问题


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" />        
        

The above snippet successfully adds an input field to the ul when the button is clicked. However when I add attributes to the input field the submit button no longer works.

    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" />        

Thanks.


回答1:


You have to either escape("\"") the double quotes inside the string or use single quotes("'") in the place of double quotes to fix your issue.

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);
}

The solution by escaping the double quotes,

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


来源:https://stackoverflow.com/questions/36532484/innerhtml-or-other-method-append-li-to-ul-with-input-including-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!