我目前正在设计一个允许用户定义一些逻辑的 GUI。我不希望它变得太复杂,所以我将它限制在一组括号内。因此,我们的想法是检查在左括号和右括号之间是否没有任何其他左括号。
例如。IF ( a + b OR **(** b+ c)
会警告错误。
所以我决定了以下路线:
- 找到第一个开括号
- 找到第一个右括号
- 使用这些索引搜索并找到任何开括号
- 如果找到任何开括号,则显示错误
- 继续循环任何其他逻辑
这是代码。我认为它非常可怕,我相信一定有更好的方法来做到这一点。某种 IndexOf 可能。
<select rel="OpenBracket" id="open1">
<option value=""></option>
<option value="(">(</option>
</select>
Some True/Fale here
<select rel="CloseBracket" id="close1">
<option value=""></option>
<option value=")">)</option>
</select>
AND
<br />
<select rel="OpenBracket" id="open2">
<option value=""></option>
<option value="(">(</option>
</select>
Some True/Fale here
<select rel="CloseBracket" id="close2">
<option value=""></option>
<option value=")">)</option>
</select>
<button onclick="javascript:TestingRules();">Check</button>
function GetOpenBrackets() {
var openBracketArray = [];
jQuery('[rel="OpenBracket"]').each(function() {
if (jQuery(this).val() == "(") {
openBracketArray.push(jQuery(this).attr('id'));
} else {
openBracketArray.push(jQuery(this).val());
}
});
return openBracketArray;
}
function GetCloseBrackets() {
var closeBracketArray = [];
jQuery('[rel="CloseBracket"]').each(function() {
if (jQuery(this).val() == "(") {
closeBracketArray.push(jQuery(this).attr('id'));
} else {
closeBracketArray.push(jQuery(this).val());
}
});
return closeBracketArray;
}
function TestingRules() {
var openBrackets = GetOpenBrackets();
var closeBrackets = GetCloseBrackets();
var closeBracketIndex;
var openBracketIndex;
for (openBracketIndex in openBrackets) {
if (openBrackets[openBracketIndex] !== "") {
var foundCloseBracketIndex = -1;
for (closeBracketIndex in closeBrackets) {
if (openBracketIndex <= closeBracketIndex) {
if (closeBrackets[closeBracketIndex] !== "") {
foundCloseBracketIndex = closeBracketIndex;
break;
}
}
}
if (foundCloseBracketIndex > -1) {
var openBracketCheck;
for (openBracketCheck in openBrackets) {
if (openBracketIndex < openBracketCheck && closeBracketIndex >= openBracketCheck) {
if (openBrackets[openBracketCheck] !== "") {
alert('error');
}
}
}
}
}
}
// for testing:
// console.log(OpenBracketArray.length);
}