函数无法在JavaScript中正确执行

时间:2019-05-22 21:42:55

标签: javascript php

我在JavaScript中具有此功能,该功能应用于计算在php中选择的产品的总价。当我加载页面时,控制台将日志记录在我的函数工作范围之外,但其中的日志记录则不会。我的代码中是否存在导致其无法执行的错误?

<?php
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      ?>
      <tr>
          <td><?= htmlentities($row['id']); ?></td>
          <td><?= htmlentities($row['Article']); ?></td>
          <td><?= htmlentities($row['Prix']); ?></td>
          <td><?= htmlentities($row['PrixRetour']); ?></td>
          <td><?= htmlentities($row['QuantiteeMaximale']); ?></td>
          <td><?= htmlentities($row['Projet']); ?></td>
          <td><input data-price='<?= floatval($row['Prix']); ?>' data-max-quantity='<?= intval($row['QuantiteeMaximale']); ?>' type="number" name="quantity"></td>
      </tr>
      <?php
    }
    ?>
    </table>
    <p>Grand Total: $<span id='grandTotal'></span></p>
    <script>
        console.log("test1");
        function calTotal() {
            console.log("test2");
            const tableEl = document.getElementById('articles')
            const grandTotalEl = document.getElementById('grandTotal')
            const inputEls = tableEl.querySelectorAll('input[name=quantity]')
            const updateGrandTotal = (grandTotalEl, inputEls) => {
                grandTotalEl.innerText = inputEls.reduce((total, inputEl) => {
                    const maxQuantity = parseInt(inputEl.dataset.maxQuantity)

                    if(parseInt(inputEl.value) > maxQuantity) inputEl.value = maxQuantity
                    if(parseInt(inputEl.value) < 0) inputEl.value = 0

                    const price = parseFloat(inputEl.dataset.price)
                    const quantity = parseInt(inputEl.value)

                    console.log("hello");

                    if(isNaN(quantity)) return total

                    return total + (price * quantity)
                }, 0)
            }
            console.log("test3");

            quantityInputEls.forEach(el => el.addEventListener('keyup', () => updateGrandTotal(grandTotalEl, inputEls)))
        };
    </script>
    <?php
} else {
    echo "0 results";
}
$conn->close();
?>

2 个答案:

答案 0 :(得分:3)

尝试用

包装函数
(function calTotal() { 
    //...contents
})();

这会将函数定义转换为IIFE,并且事件监听器将被绑定。

What is the (function() { } )() construct in JavaScript?

或者仅在calTotal();之前添加</script>

并将这些行移动到事件处理程序中,或使其可全局访问:

const grandTotalEl = document.getElementById('grandTotal')
const inputEls = tableEl.querySelectorAll('input[name=quantity]')

好,像这样更改代码:

<script> 
    function calTotal() {
        const updateGrandTotal = () => {
            const tableEl = document.getElementById('articles')
            const grandTotalEl = document.getElementById('grandTotal')
            const inputEls = tableEl.querySelectorAll('input[name=quantity]')
            grandTotalEl.innerText = inputEls.reduce((total, inputEl) => {
                const maxQuantity = parseInt(inputEl.dataset.maxQuantity)
                if(parseInt(inputEl.value) > maxQuantity) inputEl.value = maxQuantity
                else if(parseInt(inputEl.value) < 0) inputEl.value = 0

                const price = parseFloat(inputEl.dataset.price)
                const quantity = parseInt(inputEl.value)

                console.log("hello");

                if(isNaN(quantity)) return total

                return total + (price * quantity)
            }, 0)
        }

        quantityInputEls.forEach(el => el.addEventListener('keyup', () => updateGrandTotal(grandTotalEl, inputEls)))
    };
</script>

然后,您可以在开发人员工具窗口中对其进行调试,以查看不起作用的地方。

答案 1 :(得分:0)

// Create javascript-only function for loaded DOM
function readyFired(callback) {
    document.readyState != 'complete' ? setTimeout('readyFired(' + callback + ')', 1) : callback();
}

// DOM is fully-loaded and ready to calculate the total
readyFired(function() {
    calTotal();
});
相关问题