首页 > 解决方案 > 如何汇总价格表中的值?

问题描述

我该如何编写一个在特许摊位上汇总用户账单的总函数?这是一张照片,每个按钮都附有一个特定的价格,并在单击时添加到总数中。我怎样才能让所有显示的价格相加并显示在我的总框中?感谢您提前提供任何帮助! 雅

项目选择功能:

function orderUp(val) {
            switch(val){
                case "hb":
                if(!voidItem.checked){
                    hbQty++
                    hbSub += 3.00
                    }else{
                        if(hbQty >0){
                            hbQty--
                            hbSub -= 3.00
                        }
                    }
                    break;
                case "cb":
                if(!voidItem.checked){
                    cbQty++
                    cbSub += 3.50
                    }else{
                        if(cbQty >0){
                            cbQty--
                            cbSub -= 3.50
                        }
                    }
                    break;

显示结果的函数:

function recieptOut(){
            var outputStr = ""
            if (hbQty > 0){
                outputStr += "<div class = 'row'><div class = 'col'>" + hbQty + "</div>"
                outputStr += "<div class='col'>" + hbName + "</div>"
                outputStr += "<div class='col'>" + hbSub + "</div></div>"
                }
            if (cbQty > 0){
                outputStr += "<div class = 'row'><div class = 'col'>" + cbQty + "</div>"
                outputStr += "<div class='col'>" + cbName + "</div>"
                outputStr += "<div class='col'>" + cbSub + "</div></div>"   
            }

标签: javascripthtmlfunction

解决方案


你有一个非常广泛的问题,但我可以告诉你在树林里很遥远。我希望这个答案有助于向您展示一些完成任务的方法 -

<body>

  <main id="app"><main>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>

  <script src="shop.js"></script>

  <script>
    /* items on the menu */
    const menuItems =
      [ { name: "Hamburger", price: 3.00 }
      , { name: "Hotdog", price: 2.50 }
      , { name: "Nachos", price: 3.00 }
      , { name: "Chips", price: 0.75 }
      , { name: "Cheeseburger", price: 3.50 }
      , { name: "Bottled Water", price: 2.00 }
      , { name: "Fries", price: 2.50 }
      ]

    /* where to display app */
    const main =
      document.querySelector("main")

    /* run the shop */
    runShop(main, menuItems)
  </script>
</body>

shop.js

runShop函数需要一个元素来绘制商店和可供订购的商品 -

const initialState =
  { cart: [] }

const runShop = (root, items = []) => {
  const menu = makeMenu(items)
  const cart = makeCart()
  const total = makeTotal()
  const reset = makeButton("New Order", newOrder)

  root.appendChild(menu)
  root.appendChild(cart)
  root.appendChild(total)
  root.appendChild(reset)

  let state = initialState

  dispatch = (action) => {
    state = responder(state, action)
    draw(state, { menu, cart, total })
  }

  dispatch({ action: "NEW ORDER" })
}

正如我们所看到的,该runShop函数也将工作分解为更小的部分。这是makeMenu部分 -

const makeMenu = (items = []) => {
  const e = document.createElement("div")
  for (const i of items)
    e.appendChild(makeButton(i.name, addToOrder(i)))
  return e
}

const makeButton = (text, onclick) => {
  const e = document.createElement("button")
  e.appendChild(document.createTextNode(text))
  e.onclick = onclick
  return e
}

我们也继续像这样对其他部分进行分解,makeCart并且makeTotal-

const makeCart = () => {
  return document.createElement("div")
}

const makeCartItem = (item = {}) => {
  const e = document.createElement("div")
  const t = `${item.name} x ${item.qty} (${drawMoney(item.price)} each)`
  e.appendChild(document.createTextNode(t))
  return e
}

const makeTotal = () => {
  return document.createElement("div")
}

现在我们需要一条去draw商店的路。这个函数调用我们也实现的函数drawMoney——calcTotal

const draw = (state = {}, { menu, cart, total }) => {
  /* menu */
  // no changes...

  /* cart */
  cart.textContent = ""
  for (const item of state.cart)
    cart.appendChild(makeCartItem(item))

  /* total */
  total.textContent =
    `Total: ${drawMoney(calcTotal(state.cart))}`
}

const drawMoney = (m = 0) =>
  m.toLocaleString
    ( "en-US"
    , { style: "currency" , currency: "USD" }
    )

const calcTotal = (items = []) =>
  items.reduce
    ( (total, { qty = 0, price = 0 }) =>
        total + (qty * price)
    , 0
    )

菜单按钮调用addToOrder(item)和重置按钮调用newOrder。这些是对商店的简单调用,dispatchrunShop-

const addToOrder = (item = {}) => event =>
  dispatch({ action: "ADD ITEM", item })

const newOrder = event =>
  dispatch({ action: "NEW ORDER" })

responder接收来自的电话,并dispatch为您提供一个地方来为每个用户操作更新商店的状态 -

const responder = (state, action) => {
  switch (action.action) {

    case "NEW ORDER":
      return initialState

    case "ADD ITEM":
      return { ...state, cart: insert(state.cart, action.item) }

    /* implement other actions */
    // case ...

    default:
      throw Error(`unsupported action ${action.action}`)
  }
  return state
}

"NEW ORDER"动作很容易处理,我们只需返回空状态,initialState. 必须在"ADD ITEM"中插入一个项目state.cart。我们使用insert辅助函数是因为我们想要更好地控制项目的添加方式 -

  • 如果该商品尚未在购物车中,请将其添加到购物车中qty = 0
  • 否则,将匹配项更新qtyqty + 1
const { fromJS } = require("immutable")

const insert = (cart = [], item = {}) => {
  /* find item in cart? */
  const location =
    cart.findIndex(i => i.name === item.name)

  /* insert new item */
  if (location === -1)
    return [...cart, { ...item, qty: 1 } ]

  /* update existing item */
  else
    return fromJS(cart)
      .update
        ( location
        , item => item.update("qty", n => n + 1)
        )
      .toJS()
}

代码演示

点击下方的“运行代码片段”,可以看到这个程序在你自己的浏览器中运行——

<main id="app"><main>

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.min.js"></script>

<script>
  /* shop.js */
  const { fromJS } = Immutable;

  let dispatch = _ => {
    throw Error("must initialize shop first")
  }

  /* element constructors */
  const makeMenu = (items = []) => {
    const e = document.createElement("div")
    for (const i of items)
      e.appendChild(makeButton(i.name, addToOrder(i)))
    return e
  }

  const makeButton = (text, onclick) => {
    const e = document.createElement("button")
    e.appendChild(document.createTextNode(text))
    e.onclick = onclick
    return e
  }

  const makeCart = () => {
    return document.createElement("div")
  }

  const makeCartItem = (item = {}) => {
    const e = document.createElement("div")
    const t = `${item.name} x ${item.qty} (${drawMoney(item.price)} each)`
    e.appendChild(document.createTextNode(t))
    return e
  }

  const makeTotal = () => {
    return document.createElement("div")
  }

  /* actions */
  const addToOrder = (item = {}) => event =>
    dispatch({ action: "ADD ITEM", item })

  const newOrder = event =>
    dispatch({ action: "NEW ORDER" })


  /* renderers */
  const draw = (state = {}, { menu, cart, total }) => {
    /* menu */
    // no changes...

    /* cart */
    cart.textContent = ""
    for (const item of state.cart)
      cart.appendChild(makeCartItem(item))

    /* total */
    total.textContent =
      `Total: ${drawMoney(calcTotal(state.cart))}`
  }

  const drawMoney = (m = 0) =>
    m.toLocaleString
      ( "en-US"
      , { style: "currency" , currency: "USD" }
      )

  const calcTotal = (items = []) =>
    items.reduce
      ( (total, { qty = 0, price = 0 }) =>
          total + (qty * price)
      , 0
      )

  /* state */
  const initialState =
    { cart: [] }

  const responder = (state, action) => {
    switch (action.action) {
      case "NEW ORDER":
        return initialState
      case "ADD ITEM":
        return { ...state, cart: insert(state.cart, action.item) }
      default:
        throw Error(`unsupported action ${action.action}`)
    }
    return state
  }

  const insert = (cart = [], item = {}) => {
    /* find item in cart? */
    const location =
      cart.findIndex(i => i.name === item.name)

    /* insert new item */
    if (location === -1)
      return [...cart, { ...item, qty: 1 } ]

    /* update existing item */
    else
      return fromJS(cart)
        .update
          ( location
          , item => item.update("qty", n => n + 1)
          )
        .toJS()
  }

  /* run */
  const runShop = (root, items = []) => {
    const menu = makeMenu(items)
    const cart = makeCart()
    const total = makeTotal()
    const reset = makeButton("New Order", newOrder)

    root.appendChild(menu)
    root.appendChild(cart)
    root.appendChild(total)
    root.appendChild(reset)

    let state = initialState

    dispatch = (action) => {
      state = responder(state, action)
      draw(state, { menu, cart, total })
    }

    dispatch({ action: "NEW ORDER" })
  }
</script>

<script>
  /* items on the menu */
  const menuItems =
    [ { name: "Hamburger", price: 3.00 }
    , { name: "Hotdog", price: 2.50 }
    , { name: "Nachos", price: 3.00 }
    , { name: "Chips", price: 0.75 }
    , { name: "Cheeseburger", price: 3.50 }
    , { name: "Bottled Water", price: 2.00 }
    , { name: "Fries", price: 2.50 }
    ]

  /* where to display app */
  const main =
    document.querySelector("main")

  /* run the shop */
  runShop(main, menuItems)
</script>


评论

我知道这可能需要考虑很多,但希望这能向您展示如何组织数据以及将大问题分解为较小部分的一些实用方法。程序的每个部分都可以合理扩展,以适应您的其他需求。

我不确切知道您来自哪里,但是当您遇到具体问题时,我很乐意为您提供帮助。这里介绍的代码结构与ReactJS密切相关。我强烈鼓励学习其他人如何解决您的问题,以便您了解各种方法的优缺点。


推荐阅读