单击按钮后Javascript代码消失

2022-01-19 00:00:00 return javascript

我正在尝试制作小计计算工具,但我无法继续,因为我不知道问题出在哪里.提交表单或单击按钮后,一切都很快消失了.

I'm trying to make a sub-total calculation tool, but I can't continue because I don't know what the problem is. When the form is submitted, or the button is clicked, everything quickly disappears.

这是小提琴 :: http://jsfiddle.net/xFmBK/

我一无所知...

    function calcSub(){

        var input = document.getElementById('fld'),
            subTotal = document.getElementById('sub-total'),
            tax = document.getElementById('tax'),
            total = document.getElementById('total');

        var subTotalCalc = input.value / 1.06;

        var flag = true;


        if(input.value == "" || input.value == null){
            alert("Please enter in a total!");
            return false;
        } else {
            subTotal.innerHTML = "Subtotal:" + " " + "$" + subTotalCalc;
            tax.innerHTML = "Tax:" + " " + "$" + input.value - subTotalCalc;
            total.innerHTML = input.value;
            return flag;
        }

    }

推荐答案

发生这种情况是因为您的提交按钮实际上在某些操作上执行了表单提交,并且页面正在刷新.有一些方法可以修复行为,例如:

That happens because your submit button actually does a form submit on some action and page is being refreshed. There are some ways to fix behavior, such as:

让你的提交按钮只是一个按钮:<input type="button">实际上您似乎不需要那里的表格

make your submit button just a button: <input type="button"> actually doesn't seem you need a form there

或将 return false 添加到 onClick 处理程序:

or add return false to onClick handler:

<button type="submit" onclick="calcSub(); return false;">Calculate</button><br>

相关文章