Firefox中的JavaScript onchange,onblur和焦点怪异

时间:2011-01-09 17:46:56

标签: javascript firefox focus onchange onblur

在我的表单上,我有一个折扣字段,可以从总帐单中取出一笔金额(用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_bill拨打onblur时,它可以在IE中使用,但仍然无法在Firefox中使用。我试图使用一个确认框而不是一个警告框,但这也不起作用(加上我不想要两个按钮,我只是一个“确定”按钮)。

如果用户通过点击其他字段离开该字段,或者如果折扣金额大于总帐单,则如何确保焦点返回到折扣字段?

2 个答案:

答案 0 :(得分:3)

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

我自己没有尝试过,但基本上建议用

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

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

答案 1 :(得分:-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;
        }

    }