如何在JQuery中使用if条件来自定义消息规则?

时间:2018-01-12 18:39:27

标签: jquery jquery-ui

我想添加带条件的JQuery规则消息,条件x的方法,显示messageX以及是否显示messageY

这是我的代码:

addRuleAmount: function($element) {
        $element.rules("add", {
            ReqAmount : true, // function
            validationAmount : true, // function
            messages: {
                ReqAmount : "Required Amount !!",
                validationAmount : ($("#product_Type option:selected").attr('id') ==='car' ? "the amount must be between -100 and 100." : "the amount must be between 0 and 100.") 
            }
        });
    },

1 个答案:

答案 0 :(得分:1)

如果您正在使用某些静态关联,则可以考虑使用对象。

var messages = {
  car: "The amount must be between -100 and 100.",
  box: "The amount must be between 0 and 100.",
  wrench: "The amount must be between 0 and 1."
};

这为您提供了更多关联方法。所以你可以这样称呼它:

addRuleAmount: function($element) {
  $element.rules("add", {
    ReqAmount : true, // function
    validationAmount : true, // function
    messages: {
      ReqAmount : "Required Amount !!",
      validationAmount : messages[$("#product_Type option:selected").attr("id")]
    }
  });
}