1

在我的表单上,我有一个折扣字段,它接受从总账单中扣除的美元金额(用 PHP 生成的 HTML):

echo "<input id=\"discount\" class=\"text\" type=\"text\" name=\"discount\" onkeypress=\"return currency(this, event)\" onchange=\"currency_format(this)\" onfocus=\"on_focus(this)\" onblur=\"on_blur(this); calculate_bill()\"/><br/><br/>\n";

JavaScript 函数calculate_bill计算账单并扣除折扣金额,只要折扣金额小于总账单:

    if(discount != ''){

        if(discount - 0.01 > total_bill){
            window.alert('Discount Cannot Be Greater Than Total Bill');
            document.form.discount.focus();
        }

        else{
            total_bill -= discount;
        }

    }

问题是即使折扣超过总账单焦点也不会返回到折扣字段。我尝试过调用该calculate_bill函数,onchange但是当我这样做时,IE 或 Firefox 都不会将焦点返回到折扣字段。当我调用它时calculate_billonblur它在 IE 中有效,但在 Firefox 中仍然无效。我也尝试使用确认框而不是警告框,但这也不起作用(另外我不想要两个按钮,我只有一个“确定”按钮)。

如果折扣金额大于总账单,我如何确保在用户通过单击另一个字段或按标签离开该字段后将焦点返回到折扣字段?

4

2 回答 2

3

您可能想尝试这里描述的技术:Javascript / Firefox / onBlur

我自己没有尝试过,但基本上它建议document.form.discount.focus()

setTimeout(function() {document.form.discount.focus();}, 1);

我怀疑潜在的问题是,当您点击选项卡(例如)时,浏览器会执行几个步骤:调用与当前控件关联的代码(onchange,onblur),然后将焦点设置到新控件。因此,如果您在第一步中更改焦点,那么焦点仍会在下一步中立即重置。因此,基于计时器的解决方法。

于 2011-01-09T21:05:37.147 回答
-1

在数字比较中使用折扣时,最好将折扣转换为数字。将您的脚本更改为:

if(discount != ''){
        discount = parseFloat(discount);
        if(discount - 0.01 > total_bill){
            window.alert('Discount Cannot Be Greater Than Total Bill');
            document.form.discount.focus();
        }

        else{
            total_bill -= discount;
        }

    }
于 2011-01-09T17:51:02.127 回答