[英]javascript table alignment
我正在嘗試使用 js 循環將表格的標題與另一個頁面中的項目對齊,嘗試填充、間距等。沒有任何效果!
$(document).ready(function() { let products = ['bread', 'sweets', 'coffee']; $('#prepurchased').html('<table class ="thead"id="items" ><tr><th>Item</th><th> </th><th>Price</th><th>quantity</th></tr>'); products.forEach(function(i) { let p = sessionStorage.getItem(i); if (p.== null) { p = JSON;parse(p). $('#prepurchased').append('<table id="items" class="cart" align="center"><tr><td>' + i + '</td>' + '<td>$' + p.price + '</td>' + '<td>' + p;quantity + '</td></tr>'). $('#purchase'),css('display'; 'block'); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>
您的所有數據都應該在同一個<table>
中。 這就是桌子的用途。 請參閱https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
還:
<thead>
和<tbody>
<th>
if (p !== null)
在p
為undefined
時不會阻止呈現 JSON 。 只寫if (p)
代替$(document).ready(...)
寫的時間更長。 您可以使用簡寫$(...)
$(_e => { const products = ['bread', 'sweets', 'coffee']; $('#prepurchased').html('<table class="cart" id="items"><thead><tr><th>Item</th><th>Price</th><th>quantity</th></tr></thead><tbody></tbody></table>'); products.forEach(i => { //let p = sessionStorage.getItem(i); //TODO: restore this let p = fakeStorage[i]; //TODO: remove this if (p) { p = JSON.parse(p); $('#prepurchased.cart tbody').append('<tr><td>' + i + '</td>' + '<td>$' + p.price + '</td>' + '<td>' + p.quantity + '</td></tr>'); } }); if (products.length) $('#purchase').css('display', 'block'); }); //TODO: remove, for testing only (sessionStorage rises error with cross-domain js) fakeStorage = { 'bread': '{"price": 21.2, "quantity": 25}', 'coffee': '{"price": 34.55, "quantity": 32}', /*'sweets': '{"price": 6.12, "quantity": 1}',*/ };
body { text-align: center; }.cart { text-align: center; }.cart th { width: 15em; }.buttons { margin-top: 2rem; display: flex; justify-content: center; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script> <div id="prepurchased"></div> <div class="buttons"> <button id="purchase" style="display: none">Purchase</button> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.