target.status值未定义

时间:2018-12-14 12:23:09

标签: javascript

var getOptArray = function (opt) {
    var len = opt.length;
    var res = [];
    for (var i = 0; i < len; i++) {
        res.push({text: (opt[i].text), value: opt[i].value, icon: opt[i].icon, color: opt[i].color});
    }
    return res;
}

var BLOG_CATEGORY_STATUS = {
    prop: {text: "status", defval: false, class: "", size: "text-sm", margin: "m-r-xs", editable: [1, 2], tooltip: true},
    publish: {text: "publishing", value: 1, icon: "fa fa-play", color: "green", question: "Publish"},
    pause: {text: "paused", value: 2, icon: "fa fa-pause", color: "warning", question: "Pause"},
    deleted: {text: "deleted", value: 3, icon: "fa fa-trash", color: "danger", question: "Delete"},
    optArr: function () {
        return getOptArray([this.publish, this.pause, this.deleted]);
    },
    /**
     * opt example -> {status: foo, categoryId: fooValue, callback: fooFunction}
     * @param {type} opt
     */
    buildButton: function (opt) {
        opt = opt || {};
        var optArray = this.optArr();
        var targetStatus = optArray[(opt.status) - 1];
        console.log(targetStatus);
        console.log(targetStatus.color); //prints "warning"
        console.log(targetStatus.question); //prints "undefined"

        var but = {}; 
        return but;
    }
};


$(function () { 
    BLOG_CATEGORY_STATUS.buildButton({categoryId: 1 
            , status: 2
            , callback: function () {
                console.log("test");
            }})
});

我编辑代码以在jsfiddle中添加为问题。准备在jsfiddle中运行

在buildButton函数中,targetStatus.color是警告,对于同一对象,targetStatus.question未定义。看不到我想念的东西。

1 个答案:

答案 0 :(得分:3)

您可能从question返回的值中缺少getOptArray数据:

res.push({
  text: opt[i].text, 
  value: opt[i].value, 
  icon: opt[i].icon, 
  color: opt[i].color, 
  question: opt[i].question    // <- here
});

在此期间,您可能应该将这一行重写为:

res.push(opt[i]);