【问题标题】:How to change label color when input field receives text?输入字段接收到文本时如何更改标签颜色?
【发布时间】:2018-05-25 23:07:19
【问题描述】:

当我将我的 Javascript 链接到多个页面时,我对为什么会收到此错误感到困惑。我正在尝试使用 Javascript 来更改表单标签的颜色,因为它的输入字段包含文本。它在登录部分工作正常,但当我将它链接到 SignUp.html 文件时,它不起作用并给我一个错误。这是我在 codepen 上的项目的链接,如果你不想举例说明我在说什么。非常感谢任何帮助!

// LOGIN INPUT VARIABLES
let usernameInput = document.querySelector("#usernameInput");
let passwordInput = document.querySelector("#passwordInput");
// SIGN UP INPUT VARIABLES
let firstNameInput = document.querySelector("#firstNameInput");
let lastNameInput = document.querySelector("#lastNameInput");

usernameInput.addEventListener("input", function() {
    document.querySelector("#usernameLabel").style.color = "#98589e";
    if (usernameInput.value == '') {
        document.querySelector("#usernameLabel").style.color = "#b9c0c8";
    }
});

passwordInput.addEventListener("input", function() {
    document.querySelector("#passwordLabel").style.color = "#98589e";
    if (passwordInput.value == '') {
        document.querySelector("#passwordLabel").style.color = "#b9c0c8";
    }
});

firstNameInput.addEventListener("input", function() {
    document.querySelector("#firstNameLabel").style.color = "#98589e";
    if (firstNameInput.value == '') {
        document.querySelector("#firstNameLabel").style.color = "#b9c0c8";
    }
});

lastNameInput.addEventListener("input", function() {
    document.querySelector("#lastNameLabel").style.color = "#98589e";
    if (lastNameInput.value == '') {
        document.querySelector("#lastNameLabel").style.color = "#b9c0c8";
    }
});

https://codepen.io/EricGFig/project/editor/ZgPgRe

【问题讨论】:

  • 你能附上你得到的具体错误信息吗?
  • 您得到的错误是,当您尝试查找输入标签时,它返回 null。你需要看看是不是命名问题
  • @NocNit 这是错误消息 -> Uncaught TypeError: Cannot read property 'addEventListener' of null at scripts.js:8

标签: javascript html css dom-events


【解决方案1】:

你的错误是

未捕获的类型错误:无法读取 null 的属性“addEventListener”

它指向第 8 行。确实,在您的 signUp.html 文件中,您没有名为 #usernameInput 的元素(实际上也没有 #passwordInput)。

所以usernameInputpasswordInputsignUp.html 中加载此文件时都未定义(它们仅在logIn.html 中加载时定义)

因此,您不应该为两个页面使用相同的 JavaScript 文件。

signUp.html 页面应该只有以下 JavaScript 代码:

let firstNameInput = document.querySelector("#firstNameInput");
let lastNameInput = document.querySelector("#lastNameInput");

firstNameInput.addEventListener("input", function() {
    document.querySelector("#firstNameLabel").style.color = "#98589e";
    if (firstNameInput.value == '') {
        document.querySelector("#firstNameLabel").style.color = "#b9c0c8";
    }
});

lastNameInput.addEventListener("input", function() {
    document.querySelector("#lastNameLabel").style.color = "#98589e";
    if (lastNameInput.value == '') {
        document.querySelector("#lastNameLabel").style.color = "#b9c0c8";
    }
});

如果您真的想保留单个 JavaScript 文件,请考虑使用函数来分隔您的代码。例如,有一个用于登录样式处理的函数和另一个用于注册样式处理的函数。

【讨论】:

  • 谢谢你 x 100!感谢您的帮助,我试图解决这个问题已经有一段时间了。我正在学习 javascript,现在很生疏,不确定如何使用您提到的函数来做到这一点,但制作两个文件肯定有帮助。再次感谢您!
  • 没问题@EricGFig,别担心,它会随着一些练习而来。考虑接受答案/支持以供将来参考。顺便说一句,你在 codepen 上的项目看起来真的很棒!
  • 哈哈谢谢!我尝试支持您的回答,但它说我没有足够的声誉,对不起!对stackoverflow来说有点新,smh,最近才开始编码。
  • 是的,我忘了你还不能投票,但是,你总是可以接受答案 (see here on how)。 SO 是学习编码和帮助他人的好地方。
【解决方案2】:

您的代码失败的原因是您尝试在不存在的元素(null)上附加事件侦听器。

为了解决这个问题,要么创建两个单独的 JS 文件,要么在你的监听器周围添加 if 语句:

// LOGIN INPUT VARIABLES
let usernameInput = document.querySelectorAll(".usernameInput");
let passwordInput = document.querySelectorAll(".passwordInput");
// SIGN UP INPUT VARIABLES
let firstNameInput = document.querySelectorAll(".firstNameInput");
let lastNameInput = document.querySelectorAll(".lastNameInput");

if (usernameInput) {
  usernameInput.addEventListener("input", function() {
    document.querySelector("#usernameLabel").style.color = "#98589e";
    if (usernameInput.value == '') {
        document.querySelector("#usernameLabel").style.color = "#b9c0c8";
    }
  });
}

if (passwordInput) {
  passwordInput.addEventListener("input", function() {
    document.querySelector("#passwordLabel").style.color = "#98589e";
    if (passwordInput.value == '') {
        document.querySelector("#passwordLabel").style.color = "#b9c0c8";
    }
  });
}

if (firstNameInput) {
  firstNameInput.addEventListener("input", function() {
    console.log('!!');
    document.querySelector("#firstNameLabel").style.color = "#98589e";
    if (firstNameInput.value == '') {
        document.querySelector("#firstNameLabel").style.color = "#b9c0c8";
    }
  });
}

if (lastNameInput) {
  lastNameInput.addEventListener("input", function() {
    document.querySelector("#lastNameLabel").style.color = "#98589e";
    if (lastNameInput.value == '') {
        document.querySelector("#lastNameLabel").style.color = "#b9c0c8";
    }
  });
}

【讨论】:

    【解决方案3】:

    正如前面其他答案所述,代码失败是因为它试图找到一个不存在的 DOM 对象。

    我处理这个问题的方法是使用 CSS 类。我会将您的 JS 替换为:

    var trigger = document.getElementsByClassName('input-trigger')
    for(var i = 0; i < trigger.length; i++) {
      trigger[i].addEventListener("input", addListener);
    }
    
    function addListener() {
        var labels = this.parentNode.childNodes;      
        for(var i = 0; i < labels.length; i++) {
            if (labels[i].className == 'input-validate') {
                if (this.value === '') {        
                  labels[i].style.color = "#b9c0c8";
                } else {
                  labels[i].style.color = "#98589e";
                }
            }
        }
    }
    

    然后,您只需将“input-trigger”类添加到要触发颜色更改的输入,并将“input-validate”添加到要更改颜色的标签。

    上面的代码更简洁。它由第一个类触发,然后查看触发元素的父元素,然后选择该父元素内具有“input-validate”类的任何标签。

    这是一个 sn-p 示例:

    var trigger = document.getElementsByClassName('input-trigger')
    for(var i = 0; i < trigger.length; i++) {
      trigger[i].addEventListener("input", addListener);
    }
    
    
    function addListener() {
     	var labels = this.parentNode.childNodes;      
        for(var i = 0; i < labels.length; i++) {
          if (labels[i].className == 'input-validate') {
          	if (this.value === '') {      	
              labels[i].style.color = "#b9c0c8";
            } else {
              labels[i].style.color = "#98589e";
            }
          }
        }
     }
    <ul class="form-list">
      <li class="form-list-row">
        <label id="usernameLabel" class='input-validate'>Username or Email</label><br>
        <input id="usernameInput" class='input-trigger' type="text" required>
      </li>
      <li class="form-list-row">
        <label id="passwordLabel" class='input-validate'>Password</label><br>
        <input id="passwordInput" class='input-trigger' type="password" required>
      </li>
    </ul>

    虽然给出的任何其他示例都可以,但我总是更喜欢尝试编写简洁、可重用的代码。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2018-03-09
      • 2010-10-15
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多