我设置了一个包含内容的popover,其内容包含thead
和tbody
及其唯一ID的表格。如果我在浏览器控制台上手动编写document.getElementById("servicesEx-popTable_content");
,控制台会向我显示该元素。但是,当我动态设置innerHTML
时,错误显示为Cannot read property 'innerHTML' of null.
当我勾选复选框时,应在tbody
中插入一行,当我取消选中该复选框时,应删除插入的行。
document.addEventListener("click", function(x) {
if (x.target && x.target.id === "cbox") {
if (x.target.checked === true) {
var t = document.getElementById("servicesEx-popTable_content");
t.innerHTML += "<tr><td id='popover-1'></td>some name<td>1</td><td>$50</td></tr>";
} else {
var t = document.getElementById("popover-1");
t.parentNode.removeChild(t);
}
}
});
$(function() {
$('[data-toggle="popoverEx"]').popover({
container: 'body',
placement: 'bottom',
html: true,
viewport: 'body',
content: function() {
return "<table class='table services-popTable'><thead><tr><th>Name</th><th>Quantity</th><th>Price</th></tr></thead><tbody id='servicesEx-popTable_content'></tbody></table>";
}
});
});
&#13;
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div>
<span style="cursor: pointer;" data-toggle="popoverEx" data-content="">Click to see popover</span>
<label for="cbox">Click me</label>
<input type="checkbox" id="cbox">
</div>
</body>
&#13;
答案 0 :(得分:0)
答案 1 :(得分:0)
您的代码中有两个错误。
&#34;某些名字&#34;应该在第一个&#34; td&#34;,但你把它放在&#34; tr&#34;。
你应该&#34; t.parentNode.remove();&#34;而不只是删除&#34; td&#34;。
document.addEventListener("click", function(x) {
if (x.target && x.target.id === "cbox") {
if (x.target.checked === true) {
var t = document.getElementById("servicesEx-popTable_content");
t.innerHTML += "<tr><td id='popover-1'>some name</td><td>1</td><td>$50</td></tr>";
} else {
var t = document.getElementById("popover-1");
t.parentNode.remove();
}
}
});
$(function() {
$('[data-toggle="popoverEx"]').popover({
container: 'body',
placement: 'bottom',
html: true,
viewport: 'body',
content: function() {
return "<table class='table services-popTable'><thead><tr><th>Name</th><th>Quantity</th><th>Price</th></tr></thead><tbody id='servicesEx-popTable_content'></tbody></table>";
}
});
});
&#13;
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div>
<span style="cursor: pointer;" data-toggle="popoverEx" data-content="">Click to see popover</span>
<label for="cbox">Click me</label>
<input type="checkbox" id="cbox">
</div>
</body>
&#13;