简体   繁体   English

函数在JavaScript内部无法正常执行

[英]Function doesn't execute properly inside of JavaScript

I have this function inside of JavaScript that is supposed to calculate the total price of the product selected inside of php. 我在JavaScript中有这个函数,它应该计算在php中选择的产品的总价格。 When I load my page, the console logs outside of my function work but the ones inside don't. 当我加载我的页面时,控制台记录我的功能工作之外,但里面的那些没有。 Do I have a mistake in my code that causes it to not execute? 我的代码中是否存在导致其无法执行的错误?

<?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();
?>

Try wrapping your function with 尝试用你的功能包装

(function calTotal() { 
    //...contents
})();

Which will convert the function definition to IIFE, and your event listeners will be bound. 这会将函数定义转换为IIFE,并且您的事件侦听器将被绑定。

What is the (function() { } )() construct in JavaScript? JavaScript中的(function(){})()构造是什么?

Or just add calTotal(); 或者只是添加calTotal(); just before </script> 就在</script>之前

and move these lines into the event handler, or make them globally accessible: 并将这些行移动到事件处理程序中,或使它们可全局访问:

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

Ok, change your code like this: 好的,改变你的代码如下:

<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>

Then you can debug it at your developer tools window to see what's not working. 然后,您可以在开发人员工具窗口中对其进行调试,以查看哪些内容无效。

// 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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM