【问题标题】:Count the subtotal from list select option, based on clicked (' active ') element根据单击的(“活动”)元素从列表选择选项中计算小计
【发布时间】:2021-01-22 00:21:12
【问题描述】:

这是我的目标: Before anything clicked || After user select the item that they want

在我做了一些研究之后,我能够用 vue.js 做到这一点
https://jsfiddle.net/Hanstopz/Lcnxtg51/10/

但是,当我尝试使用普通 javascript 创建这个时,我被卡住了

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Form pesanan</title>
        <style>
            @import url(https://fonts.googleapis.com/css?family=Cookie);
            [v-cloak] {
              display: none;
            }
            *{
                margin:0;
                padding:0;
            }
            body{
                font:15px/1.3 'Open Sans', sans-serif;
                color: #5e5b64;
                text-align:center;
            }
            a, a:visited {
                outline:none;
                color:#389dc1;
            }
            a:hover{
                text-decoration:none;
            }
            section, footer, header, aside, nav{
                display: block;
            }
            form{
                background-color: #61a1bc;
                border-radius: 2px;
                box-shadow: 0 1px 1px #ccc;
                width: 400px;
                padding: 35px 60px;
                margin: 50px auto;
            }
            form h1{
                color:#fff;
                font-size:64px;
                font-family:'Cookie', cursive;
                font-weight: normal;
                line-height:1;
                text-shadow:0 3px 0 rgba(0,0,0,0.1);
            }
            form ul{
                list-style:none;
                font-size:20px;
                font-weight:bold;
                text-align: left;
                margin:20px 0 15px;
            }
            form ul li{
                padding:20px 30px;
                background-color:#f0f0f0;
                margin-bottom:8px;
                box-shadow:0 1px 1px rgba(0,0,0,0.1);
                cursor:pointer;
            }
            form ul li span{
                float:right;
            }

            /* ini bagian v-bind 'active' (menambahkan class ini ke li) */
            .active{  
                color: white;
                background-color: darkgreen;
            }

            div.total{
                border-top:1px solid rgba(255,255,255,0.5);
                padding:15px 30px;
                font-size:20px;
                font-weight:bold;
                text-align: left;
                color:#fff;
            }
            div.total span{
                float:right;
            }
        </style>
    </head>
    <body>
        <form id="main">
            <h1>Menu kami</h1>
            <ul id="menu">
                <!-- {{service.name}} <span>{{service.price | currency}}</span> -->
            </ul>
            <div class="total">
                Total harga:
                <!-- Total: <span>{{total() | currency}}</span> -->
            </div>
        </form>
        <script>
            const menu = [
                {   name: 'Cappucino',          price: 35000,   active: true   },
                {   name: 'Green tea latte',    price: 40000,   active: false   },
                {   name: 'Fish and chips',     price: 50000,   active: false   },
                {   name: 'Tuna sandwich',      price: 30000,   active: false   },
                {   name: 'Mineral water',      price: 8000,    active: false   },
                {   name: 'French fries',       price: 18000,   active: false   }
            ]
            menu.forEach((menu, price) => {
                document.getElementById('menu').innerHTML += "<li>" + menu.name + "<span>" + "Rp " + menu.price + "</span>" + "</li>"
            });
            
        </script>
    </body>
</html>

我设法从数组创建了显示,但是当我单击列表和计算所有活动元素的函数时,我对如何添加活动类感到困惑......请帮助我。

{更新} 在我结合 Nabir Abbas 的答案后,我可以选择并在活动元素和非活动元素之间切换。但我想做一个总数,只要它有一个活跃的元素就可以计算。价格将从基于活动链接的数组中获取...所以我尝试了这个

function totalCount() {
if ($("li").hasClass("active")) {
   document.getElementById("subtotal").innerHTML = 0 + $(menu.price);
}}

但好像不太对劲,谁能帮帮我?

【问题讨论】:

    标签: javascript html jquery vue.js


    【解决方案1】:

    这应该可行:

    const menu = [{
        id: 1,
        name: 'Cappucino',
        price: 35000,
        active: true
      },
      {
        id: 2,
        name: 'Green tea latte',
        price: 40000,
        active: false
      },
      {
        id: 3,
        name: 'Fish and chips',
        price: 50000,
        active: false
      },
      {
        id: 4,
        name: 'Tuna sandwich',
        price: 30000,
        active: false
      },
      {
        id: 5,
        name: 'Mineral water',
        price: 8000,
        active: false
      },
      {
        id: 6,
        name: 'French fries',
        price: 18000,
        active: false
      }
    ]
    
    menu.forEach((menu, price) => {
        const li = document.createElement('li')
      li.innerHTML = `${menu.name}<span>Rp ${menu.price}</span>`
      li.addEventListener('click', e => {
        li.classList.toggle('active')
        console.log('Active lements', getActiveCount())
      })
      
      document.getElementById('menu').append(li)
      
    });
    
    function getActiveCount() {
        const activeListItems = document.querySelectorAll('#menu li.active')
      return activeListItems.length
    }
    
    

    在这里,我们将事件侦听器添加到移动中的每个元素,然后再将它们附加到父元素。另外,请注意我们正在使用classList.toggle,如果active 类存在于列表项中,它将删除它,如果不存在则添加它

    2020 年 10 月 7 日编辑

    要获取活动元素的总价格,首先您必须将项目价格作为属性添加到 per li,您可以使用以下函数:

    所以上面的代码变成了:

    menu.forEach(item => {
        const li = document.createElement('li')
      li.innerHTML = `${menu.name}<span>Rp ${menu.price}</span>`
      li.setAttribute('data-price', item.price)
      li.addEventListener('click', e => {
        li.classList.toggle('active')
        console.log('Active lements', getActiveCount())
      })
      
      document.getElementById('menu').append(li)
      
    });
    

    然后:

    function getTotalPrice() {
      const activeItems = document.querySelectorAll('#menu li.active')
      return activeItems.length ? Array.from(activeItems).reduce((acc, elem) => acc+=elem.getAttribute('data-price'), 0): 0
    }
    

    【讨论】:

    • 先生,您是否添加了计算活动元素的功能? (对不起,我的语法不好)还有,我是网络开发的新手
    • @Hanstopz 是的,我添加了一个函数来计算活动元素。
    • @NabirAbbas 尝试此代码后,我看起来像“activeListItems.length”,计算有多少活动元素并在控制台中返回。但是我如何从数组中计算活动元素的价格(取“价格”)?
    • @NabirAbbas 我应该添加另一个 if 函数吗?
    • @Hanstopz 你想计算活动元素的总价吗?另外,请对这个问题投赞成票,有人无缘无故地投反对票。谢谢
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多