问题
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