【问题标题】:Javascript extend objects in variableJavascript在变量中扩展对象
【发布时间】:2009-12-11 10:36:36
【问题描述】:

我有一个包含表单字段验证消息的函数。但是,我希望有默认消息,但也有可能稍后从不同的功能(即时)添加自定义消息。我已经尝试过使用 php 并扩展一个类并添加更多消息而不是构建 javascript,但我不太高兴这样做。

function msg_text(fieldV){

msg = {
    "required":{                
        "alertText":"* This field is required"
    },
    "length":{
        "alertText":"* minimum 6 characters "
    },
    "numeric":{
        "alertText":"numbers and * only<br />minimum 3 characters"
    },
    "email":{
        "alertText":"* Invalid email address"
    },
    "no_space":{
        "alertText":"* Is Required <br /> * Space not allowed"
    }
}

return msg[fieldV].alertText;  //returns alert message

}

【问题讨论】:

    标签: javascript object


    【解决方案1】:
    变量我的{}; 函数创建函数() { var msg = {/*消息*/}; my.getMessage = 函数(键) { 返回味精[键]; } my.addMessage = 功能(键,消息) { msg[key] = 消息 } my.deleteMessage = 功能(键) { 删除味精[键]; } }

    【讨论】:

    • 感谢您的回答。如果 var msg 中不存在密钥,my.addMessage 似乎不起作用。但是,如果 var msg 中存在相同的键,它会起作用并替换消息。我试过这个:msg[key].alertText = message;
    • 我已经想通了。这段代码对我有用:msg[key] = {"alertText":message};
    猜你喜欢
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2011-09-21
    相关资源
    最近更新 更多