Javascript对象不是函数 [英] Javascript object is not a function

查看:82
本文介绍了Javascript对象不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误,我找不到原因:

I get the following error and I can't find why:


TypeError:object不是函数

TypeError: object is not a function

这是我的html:

<td><input type="text" value="" id="cash_retained" name="cash_retained" onkeyup="net_cash()" size="25"></td>
<td><input type="text" value="" id="cash_change" name="cash_change" onkeyup="net_cash()" size="25"></td>
<td><input type="text" value="0" id="net_cash" name="net_cash"></td>

这是我的js函数:

function net_cash() {
    var cash = 0;
    var retained = document.getElementById("cash_retained");
    var change = document.getElementById("cash_change");

    cash += parseInt(retained.value);
    cash += parseInt(change.value);

    if (isNaN(cash)) {
        document.getElementById("net_cash").value = "0";
    } else {
        document.getElementById("net_cash").value = cash;
    }
}

我无法看到我的生活为什么这不起作用。我有其他类似的js函数,它们发现它很好。

I can't see for the life of me why this is not working. I have other similar js functions that are finding it just fine.

推荐答案

这里的问题似乎是你有一个表单元素与您的函数同名:

It appears the problem here is that you have a form element with the same name as your function:

<td><input type="text" value="0" id="net_cash" name="net_cash"></td>

所以当你打电话给 net_cash()时你的 onkeyup 事件,它认为你指的是这个输入 DOM对象而不是同名的函数。我建议为这两件事提出单独的名称。

So when you call net_cash() in your onkeyup event, it thinks you are referring to this input DOM object rather than the function of the same name. I suggest coming up with separate names for these two things.

内联事件处理程序具有封闭的< form> 元素作为执行范围。每个具有 name 属性的表单控件都被视为该范围内的变量,而且是冲突的来源。

Inline event handlers have the enclosing <form> element as their executing scope. Each form control with a name attribute is treated as though it's a variable in that scope and that's where the conflict comes from.

这也是使用不引人注目的JavaScript 而非内联事件处理程序的另一个重要原因。如果这样做,则不必担心函数名称与元素名称冲突。有关使用内联事件处理程序的缺陷的更多信息,请参阅 onclick =vs事件处理程序

This is also yet another great reason to use unobtrusive JavaScript instead of inline event handlers. If you do that, you don't have to worry about your function names conflicting with your element names. See onclick="" vs event handler for more information on the pitfalls of using inline event handlers.

这篇关于Javascript对象不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆