【问题标题】:How do I get rid of this error? TypeError: Cannot set property 'onfocus' of null我该如何摆脱这个错误? TypeError:无法将属性“onfocus”设置为 null
【发布时间】:2020-03-05 17:41:52
【问题描述】:

所以我有一个用于<input> 表单字段的角度组件,用于模式库。我设置了所有必要的部分以使其显示和运行。但是,我添加了一些功能来提高<label> 并在字段中输入文本时保持<label> 升高或onfocus<label> 应该保持升高onblur 如果<input> 中有文本文本域。该代码几天前还在工作,没有任何改变。这是 HTML 组件:

            <div class="regular-text" id="regularFormField">
                <a href="{{HelperUrl}}" *ngIf="HelperUrl">{{HelperUrltext}}</a>          
                <span *ngIf="state == 'Validation'" class="valid"><img src="../../assets/01-green-validate-check.png" alt="valid icon">{{ValidMssg}}Valid bank number</span>
                <span *ngIf="state == 'Error'" class="error" id="wrongText"><img src="../../assets/error-icon.svg" alt="error icon">{{ErrorMssg}}We don’t recognize this email. Please try again.</span>
                <input type="{{FormType}}" id="email" aria-label="" [ngClass]="{'disabled': state == 'Disabled', 'error': state == 'Error', 'valid': state == 'Validation'}" [attr.disabled]="state == 'Disabled' ? 'disabled' : null">
                <label for="{{FormType}}" aria-label="" id="labelone" [ngClass]="{'disable-text': state == 'Disabled'}">{{FormType}}</label>
            </div>
        </div>

这里是JS代码:


  ngOnInit() {
    const input = document.getElementById("email");

    const formOutline = document.getElementById("regularFormField");
    const label = document.getElementById("labelone");

    input.onfocus = () => {
      formOutline.classList.add("focused");

    };

    input.onblur = () => {
      formOutline.classList.remove("focused");
      label.classList.add("active");

      const inputValue = (<any>document).getElementById("email").value;

      if (inputValue == "") {

        label.classList.remove("active");
      }
    };
  } // ng init


Is there anything missing? I know a fresh set of eyes helps. 

【问题讨论】:

  • 尝试使用 Angular。使用(focus)="myFocusHandler() 处理focus 事件。使用[class.active]="activeCondition" 设置类。您应该很少(如果有的话)需要手动更改 DOM
  • 因为当您调用代码时,您的退休可能还不存在。你应该对这类东西使用角度事件钩子。

标签: javascript angular forms onblur onfocus


【解决方案1】:

使用 DOM 检查器和console.log 语句来检查、调试和识别问题,然后追踪到源头。

当您的 JS 代码运行时,input 为空。这意味着没有找到 ID 为“email”的元素。

将 console.log 放在输入上方以验证这一点。然后在检查器中手动检查 DOM 元素以查看它是否存在。从那里去。

关于更改应用架构的 cmets 可能是很好的建议 - 我不使用 Angular - 但缩小范围的基本调试技术对于掌握你的技能至关重要。

你应该明白这里发生的事情。如果它确实在工作并突然停止,那么要么您确实进行了您不知道的更改,要么正在发生其他事情。无论哪种方式,您都想了解您的代码库及其操作 - 如果您确实做了导致这种情况的事情,您想知道它是什么,否则您可能会在其他地方做同样的事情,您的编程经验将感到沮丧。

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2021-05-23
    • 2019-10-24
    • 2020-02-19
    • 2023-03-06
    • 1970-01-01
    • 2019-04-18
    • 2014-08-20
    • 1970-01-01
    相关资源
    最近更新 更多