我回答这个问题有点晚了,希望你现在有一个解决方案。
最近,我也在我的一个项目中使用了 jQuery QueryBuilder,并想出了以下解决方案。
var lastOperator = [];
var rulesLengths = [];
var ruleLevel = 0;
var equationString = '';
var rulesData = {
"condition": "AND",
"rules": [
{
"id": "genderSelect",
"field": "genderSelect",
"type": "string",
"input": "select",
"operator": "equal",
"value": "Male"
},
{
"id": "ageSelect",
"field": "ageSelect",
"type": "string",
"input": "select",
"operator": "equal",
"value": "18-26"
}
],
"valid": true,
};
var expr = checkDisplayLogic(rulesData);
var flag = eval(expr);
/** Recursive function to convert json data to expression **/
function checkDisplayLogic(rulesData) {
if (rulesData['rules'] !== undefined) {
ruleLevel++;
var operator = rulesData['condition'];
lastOperator.push(operator);
rulesLengths.push(rulesData.rules.length);
equationString += '(';
$.each(rulesData.rules, function (idx, elem) {
checkDisplayLogic(elem);
if (rulesLengths[rulesLengths.length - 1] == idx + 1) {
equationString += ')';;
rulesLengths.pop();
ruleLevel--;
lastOperator.pop();
}
else {
if (lastOperator.length !== 0)
equationString += ' ' + (operator === 'AND' ? '&&' : '||' ) + ' ';
}
});
}
else {
var inputType = rulesData.input;
switch (inputType) {
case 'select':
var ctrl = $('#' + rulesData.id);
//Below logic will change depending upon the operator selected in QueryBuilder.
//In my case operator is 'equal' that's why I am using '===' operator for comparison
equationString += (ctrl.val() === rulesData.value).toString();
break;
/****** Similarly create cases for other input types QueryBuilder provide ********/
}
}
return equationString;
}
快乐编码!