如何允许表单元素具有多个类,并为错误消息连接/切片

How to allow form elements to have more than one class and concatenate / slice for error message

本文关键字:错误 消息 连接 切片 元素 表单 何允许      更新时间:2023-09-26

我正试图通过允许表单元素的标签来更改此代码有不止一节课。我知道我必须使用串联来添加错误类,并通过剪切最后一个空格后的文本来删除错误类在className值中,但我从哪里开始,我应该只修改跨度吗?

    function addErrorMessage(id, msg) {
    'use strict';
    // Get the form element reference:
    var elem = document.getElementById(id);
    // Define the new span's ID value:
    var newId = id + 'Error';
    // Check for the existence of the span:
    var span = document.getElementById(newId);
    if (span) {
        span.firstChild.value = msg; // Update
    } else { // Create new.
        // Create the span:
        span = document.createElement('span');
        span.id = newId;
        span.className = 'error'
        span.appendChild(document.createTextNode(msg));
        // Add the span to the parent:
        elem.parentNode.appendChild(span);
        elem.previousSibling.className = 'error';
    } // End of main IF-ELSE.
} // End of addErrorMessage() function.
// This function removes the error message.
// It takes one argument: the form element ID.
function removeErrorMessage(id) {
    'use strict';
    // Get a reference to the span:
    var span = document.getElementById(id + 'Error');
    if (span) {
        // Remove the class from the label:
        span.previousSibling.previousSibling.className = null;
        // Remove the span:
        span.parentNode.removeChild(span);
    } // End of IF.
} // End of removeErrorMessage() function.

为什么不使用jQuery,这样您就可以简单地使用addClass和removeClass?

http://api.jquery.com/addclass/

http://api.jquery.com/removeclass/

你还可以从hasClass之类的东西中获益。。。http://api.jquery.com/hasclass/