我正在尝试使用javascript动态填充html模板。
下面是我正在使用的内容
window.onload = function() {
document.getElementById('price_01').innerHTML = price_01;
document.getElementById('dimension_01').innerHTML = dimension_01;
}
使用在标记内定义的全局变量
var price_01 = '$8000';
var dimension_01 = '10m';
如果标记是独立的,则此操作如下所示:
<div class="w3-container">
<table class="table">
<tbody>
<tr>
<td>Price:</td>
<td id='price_01'></td>
</tr>
<tr>
<td>Dimension:</td>
<td id='dimension_01'></td>
</tr>
</tbody>
</table>
</div>
但是,当我尝试在模式中填充内容时,它不起作用:
<div class="w3-container">
<button onclick="document.getElementById('id02').style.display='block';" class="w3-button w3-black">More Details</button>
<div id="id02" class="w3-modal">
<div class="w3-container">
<table class="table">
<tbody>
<tr>
<td>Price:</td>
<td id='price_01'></td>
</tr>
<tr>
<td>Dimension:</td>
<td id='dimension_01'></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
这将返回空白。有没有办法解决这个问题?有没有比我现在所做的更优雅的解决方案?谢谢
编辑:抱歉,这并不是说它不能在模式中工作,但当你在模式内部和外部使用它时,它就不能工作了。以下是TryIt编辑器上的复制:
https://www.w3schools.com/code/tryit.asp?filename=FTJIGZ6U0XCK
发布于 2018-07-23 09:17:09
您有两个元素,每个元素的id
分别为price_01
和dimension_01
。只能有一个具有特定id
的元素。您应该改为按类名选择这些元素。
<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script type="text/javascript">
var price_01 = '$8000';
var dimension_01 = '10m';
var prices = document.getElementsByClassName("price_01");
var dimensions = document.getElementsByClassName("dimension_01");
window.onload = function() {
for(let i = 0; i < prices.length; i++){
prices[i].innerHTML = price_01;
}
for(let i = 0; i < dimensions.length; i++){
dimensions[i].innerHTML = dimension_01;
}
}
</script>
<body>
<div class="w3-container">
<h2>W3.CSS Modal</h2>
<div class="w3-container">
<table class="table">
<tbody>
<tr>
<td>Price:</td>
<td class='price_01'></td>
</tr>
<tr>
<td>Dimension:</td>
<td class='dimension_01'></td>
</tr>
</tbody>
</table>
</div>
<button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Open Modal</button>
<div id="id01" class="w3-modal">
<div class="w3-modal-content">
<div class="w3-container">
<span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">×</span>
<div class="w3-container">
<table class="table">
<tbody>
<tr>
<td>Price:</td>
<td class='price_01'></td>
</tr>
<tr>
<td>Dimension:</td>
<td class='dimension_01'></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
https://stackoverflow.com/questions/51470362
复制相似问题