Javascript 複雑な計算

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>My Playground</title>
  <style>
    table {
      border-collapse: collapse;
    }
    th {
      font-weight: normal;
      background: #eee;
    }
    th,
    td {
      padding: 4px;
      border: 1px solid;
    }
    th:nth-child(1) {
      width: 180px;
    }
    th:nth-child(2) {
      width: 180px;
    }
    td:nth-child(2) {
      text-align: right;
    }
    tr:last-child {
      font-weight: bold;
    }
    input[type="checkbox"] {
      margin-right: 8px;
    }
  </style>
</head>
<body>
  <table>
    <thead>
      <tr><th>商品名</th><th>価格</th></tr>
    </thead>
    <tbody id="items">
      <tr><td>合計 (送料込)</td><td><span id="total">0</span>円</td></tr>
    </tbody>
  </table>
  <p>
    ※ 税込価格、送料350円は5,000円以上で無料
  </p>
  <script>
    // 合計金額を0で初期化
    let total = 0;
    // 送料を定義するための変数
    let shipping;
    // HTMLからitemsというIDを持つテーブル要素を取得
    const table = document.getElementById('items');
    // HTMLからtotalというIDを持つspan要素を取得
    const totalSpan = document.getElementById('total');
    // 商品データを格納した配列
    const items = [
      {name: 'Tシャツ', price: 1200},
      {name: 'カットシャツ', price: 4200},
      {name: 'チノパン', price: 3800},
      {name: '靴下', price: 800},
    ];
    
    // すべての商品データに対して処理を行う
    items.forEach((item) => {
      // 新しいtr要素を作成
      const tr = document.createElement('tr');
      // 新しいtd要素を作成
      const nameTd = document.createElement('td');
      // 商品名のテキストを作成
      const nameText = document.createTextNode(item.name);
      // チェックボックスを作成
      const checkbox = document.createElement('input');
      // チェックボックスのタイプを設定
      checkbox.type = "checkbox";
      // チェックボックスがチェックされたときの処理
      checkbox.addEventListener('change', () => {
        // チェックされている場合、合計金額を加算
        if (checkbox.checked) {
          total += Number(item.price);
        } else {
          // チェックされていない場合、合計金額から減算
          total -= Number(item.price);
        }
        // 合計金額が5000以上または0の場合、送料は0
        if (total >= 5000 || total === 0) {
          shipping = 0;
        } else {
          // それ以外の場合、送料は350
          shipping = 350;
        }
        // 合計金額と送料を加算し、totalSpanに表示
        totalSpan.textContent = (total + shipping).toLocaleString();
      });
      // 新しいtd要素を作成
      const priceTd = document.createElement('td');
      // 価格をテキストとしてtd要素に追加
      priceTd.textContent = item.price.toLocaleString() + '円';
      // td要素にチェックボックスと商品名を追加
      nameTd.appendChild(checkbox);
      nameTd.appendChild(nameText);
      // tr要素に商品名のtd要素と価格のtd要素を追加
      tr.appendChild(nameTd);
      tr.appendChild(priceTd);
      // tr要素をテーブルの最後の行の前に挿入
      table.insertBefore(tr, table.rows[table.rows.length - 1]);
    });
  </script>
</body>
</html>

投稿者: chosuke

趣味はゲームやアニメや漫画などです

「Javascript 複雑な計算」への27件のフィードバック

  1. Honestly the simplicity is what makes this work, the topic is not buried under filler words or overly complex examples, and a quick look at elitebuyarena showed the same sensible style, I left with what I came for and no headache from over reading which is a real win these days.

  2. Started reading expecting to disagree and ended mostly nodding along, and a look at silverlaneemporium continued the pattern, content that wins agreement through evidence and reasoning rather than rhetorical force is the kind that actually shifts minds and this site clearly knows how to do that across what I have read so far.

  3. Quietly the post solved something I had been turning over without quite knowing how to phrase the question, and a look at trendydealhub extended that quiet solving, content that addresses unformulated needs is content with reader insight and this site has demonstrated that insight at a high rate across the pieces I have read recently.

  4. Now sitting back and recognising that this was a small but real win in my reading day, and a stop at crystalpinegoods extended that quiet win, the cumulative effect of small reading wins versus the cumulative effect of small reading losses is real over time and this site is contributing to the wins side of that ledger.

  5. Big thanks to whoever wrote this, you saved me a lot of time hunting for the same info on other sites, and a stop at urbancrestemporium only added more useful detail without going off topic, that kind of focus is honestly hard to come across these days when most posts wander everywhere.

  6. Looking for similar voices elsewhere has come up empty in my recent searches, and a stop at goldensproutgoods extended the search frustration, the rare site that does what no other does in quite the same way is precious and this one has clearly developed a particular approach that I have not been able to find duplicates of.

  7. A piece that read as the work of someone who reads carefully themselves, and a look at rapidgoodszone continued that informed feel, writers who are also serious readers produce work with a different quality and this site reads as the product of someone steeped in good writing rather than just generating content for an audience.

  8. Came across this through a roundabout path and now it is on my regular rotation, and a stop at frostharbormarket sealed that decision, the open web still produces serendipitous discoveries when you let the citations and references guide you rather than relying purely on algorithmic feeds for new content recommendations always.

  9. Found this through a friend who recommended it and now I see why, and a look at velvetharborgoods only strengthened that recommendation in my own mind, word of mouth still works for content that actually delivers and this site is clearly earning recommendations the old fashioned way through quality rather than marketing.

  10. Now sitting with the thoughts the post triggered rather than rushing on to the next thing, and a stop at swifttrendhub extended that reflective pause, content that earns time for thought after closing the tab is content of higher value than the merely interesting and this site has clearly produced that lasting effect today.

  11. Found this useful, the points line up well with what I have been thinking about lately, and a stop at trustedbuyerszone added some angles I had not considered yet, definitely walking away with more than I came for which is the best outcome from time spent reading online for any kind of topic.

  12. Top notch writing, every paragraph carries weight and nothing feels like filler, and a stop at silverhorizonstore reflected that same care, a rare thing on the open web these days where most pages exist for clicks rather than actual reader value or anything close to that which is honestly a real shame.

  13. Closed it feeling slightly more competent in the topic than I started, and a stop at freshcartcorner reinforced that competence boost, real learning is rare in casual online reading but it does happen sometimes and this site managed to make it happen for me today which is genuinely worth pausing to acknowledge.

  14. Liked how the writer used real examples instead of theoretical ones to make the points stick, and a stop at premiumpickzone added even more concrete examples, this is the kind of practical approach that respects readers who actually want to apply what they learn rather than just nodding along passively without doing anything useful.

  15. Thanks for putting this online without locking it behind email signups or paywalls, and a quick visit to dreamwovenbazaar kept that open feel going, content that trusts the reader to come back rather than gating access is the kind of approach I will reward with regular return visits over time happily.

  16. Found this through a search that was generic enough I did not expect quality results, and a look at epiccartcenter continued the surprisingly good experience, search engines occasionally still surface excellent independent content if you scroll past the obvious paid and high authority results which is reassuring to remember sometimes.

  17. Reading this in a quiet hour and finding it suited the quiet, and a stop at copperwindessentials extended the quiet reading mood, content that matches its own optimal reading conditions rather than fighting them is content that has been thoughtfully calibrated and this site reads as having a particular reading mood in mind throughout.

  18. Picked this for my morning read because the topic seemed worth the time, and a look at infinitybuyhub confirmed the choice was right, my morning reading slot is precious and giving it to this site felt like a good investment rather than a waste which is a higher endorsement than I usually offer for content.

  19. Felt mildly happier after reading, which sounds silly but is true, and a look at neonpickmarket extended that small mood lift, content that improves rather than degrades my mental state is content I want more of and the cumulative effect of reading sites that lift versus sites that drag is real over time.

  20. Now thinking about how this post will age over the coming years, and a stop at perfectbuycorner suggested the same durability, content built to age well rather than to capture the attention of the moment is content with a different kind of value and this site has clearly chosen the long horizon over the short one.

  21. Reading this site over the past week has changed how I evaluate content in this space, and a look at crystalbloommarket extended that recalibration, the standards I bring to reading on the topic have shifted upward as a direct result of regular exposure to this kind of work and that shift will outlast any single reading session.

  22. Skipped the comments to avoid spoilers and came back later to find them genuinely worth reading, and a stop at goodslinkstore extended that surprised respect, when the discussion below a post matches the quality of the post itself you have found something special and this site appears to attract that kind of audience.

  23. A small thing but the line spacing and font choices made reading this physically pleasant, and a look at windspirecollective maintained the same careful design, technical choices about typography are part of what makes online reading actually comfortable and this site has clearly invested in the design layer alongside the content layer carefully.

  24. Really appreciate the confidence to make a clear point rather than hedging everything, and a quick visit to frostharbormarket maintained the same direct stance, writing that takes positions rather than equivocating is more useful even when the positions are debatable because at least the reader has something to react to clearly.

  25. Thanks again for the post, I learned a couple of things I can actually use later this week, and after I went over infinitydealcenter the rest of the site looked equally promising, definitely going to spend more time here when I get a free moment over the weekend to read more carefully.

  26. Reading this gave me a small jolt of recognition for an experience I thought was just mine, and a stop at nextcartstation produced more such jolts, content that universalises private experiences without flattening them is doing genuinely useful work and this site is providing that recognition function for me reliably across topics I read.

  27. Reading this gave me a small jolt of recognition for an experience I thought was just mine, and a stop at stylishgoodszone produced more such jolts, content that universalises private experiences without flattening them is doing genuinely useful work and this site is providing that recognition function for me reliably across topics I read.

コメントを残す

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です