Javascript if 条件与子字符串

标签 javascript if-statement input substring conditional-statements

我尝试根据文本字段value_master中的输入来完成一些输入。 例如,如果我在文本字段 value_master 中输入 123,我希望每个 value_slave 字段中都有特定的文本,但如果我输入 223我想要别的东西。

我成功做到了这一点,并且在没有 if 条件的情况下工作。这样我就明白了:slave.substring 不是一个函数。使用子字符串很重要,因为根据主值的具体位置,我将有更多的字段需要完成。

    window.onload = function()
    {
        var master = document.getElementById('value_master');
        var slave = document.getElementById('value_slave');

        document.getElementById('value_master').onkeyup = function(){
            if (slave.substring(0,1).equals("1") )          
            {
                slave.value = 'you typed something starting with 1';
            }
            else {
                slave.value = 'you typed something starting with 2';
            }
        };
    };

最佳答案

您必须将代码更改为以下内容:

window.onload = function()
{
    document.getElementById('value_master').onkeyup = function() {
        var slave = document.getElementById('value_slave');
        if (slave.value.substring(0,1).equals("1") )          
        {
            slave.value = 'you typed something starting with 1';
        }
        else {
            slave.value = 'you typed something starting with 2';
        }
    };
};

slave 是代码中的元素,而不是元素的值。要获取元素的值,您必须使用element.value。此外,该值仅在窗口加载时设置一次。但没有更新。要始终使用输入的值,请将 var Slave = document.getElementById('value_slave'); 移至 onkeyup 函数内。

关于Javascript if 条件与子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55297304/

相关文章:

ios - 带有 && 操作的快速多个条件 if 语句

ios - 使用 case switch 而不是多个 if 语句来处理错误

java - 在 if 中检查 hasNextInt() 然后接收输入

html - 输入打印时内部没有文本,但在屏幕上可见

javascript - jquery单滑动 handle

javascript - GPA计算器,如何将字母输入变成数字

php - file_exists()在while循环内的php5中不起作用

Android Chrome 禁用搜索输入表单上的自动建议

javascript - 延迟 globalTick() JS 中每个 Sprite 的 tick()

javascript - MVC 4 中的数据注释不显示错误消息