javascript - 通过函数参数传递 id

标签 javascript html function getelementbyid

尝试通过将 ID 传递给函数参数来获取文本框的值。应该很容易,但我无法理解它。

JavaScript:

function checkfield(id) 
    {
        var field = document.getElementById(id);

        if (isNaN(field) == true) 
            {
                alert('You must enter a valid number!');
                field.value = "0";
                field.focus(textbox);
                field.select(textbox);
                return false;
            }
        return true;

    }

HTML:

<input type="text" id="numbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield('numbox19')"/>

错误信息

Error: Unable to get property 'value' of undefined or null reference

最佳答案

您的 ID 是 19,但您将 numberbox19 传递给 Javascript 函数。还有一些语法错误。

尝试:

<input type="text" id="numberbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield(this)"/>

和 JavaScript:

function checkfield(field) // <-- we passed the field in directly from the HTML, using 'this'
{
    alert(field.value);

    if (isNaN(field.value)) // check the value, not the field itself!
    {
        alert('You must enter a valid number!');
        field.value = "0";
        field.focus(); // not "field.focus(textbox);"
        return false;
    }
    return true;

}

这里的好处是,如果您出于任何原因决定更改 ID,您只需更改一处而不是两处。

关于javascript - 通过函数参数传递 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20200492/

相关文章:

javascript - 让我的 JS 和 HTML 表单与 Ember.js 一起使用

html - 滚动时顶部导航栏应该改变吗?

android - 避免代码重复 - 如何在 gradle 中创建函数(并调用它们)?

python - 从字典中返回一组具有共同值的键对

javascript - 如何在移动设备中显示图像而不是视频背景

javascript - 正则表达式:匹配多个单词的第一个字母

javascript - 使用 javascript 或 jquery 解析 url

html - 中心等距的空间 NavBar 元素?

php - 在 PHP 中使用 rename_function() (不工作)

Javascript:让用户选择像 Firebug 这样的 HTML 元素?