该页面上有多个问题/答案集。每个集合都被分组到一个“questionItem”类的 div 中。在每个集合中,总是有一个名为 answers[idx].SetAnser 的输入,并且可能有一个 answers[idx].Answer,其中 idx 是集合的索引。
需要解决的问题是找到所有问题集 div 元素,其中 SetAnswer 为一个值,Answer 为另一个值。这是示例html:
<div class="questionItem format">
<input name="answers[0].SetAnswer" type="hidden" value="0" />
<select name="answers[0].Answer">
<option selected="selected" value="0">(0) No</option>
<option value="1">(1) Yes</option>
<option value="-">(-) Not assessed</option>
</select>
</div>
<div class="questionItem format">
<input name="answers[1].SetAnswer" type="hidden" value="?" />
<select name="answers[1].Answer">
<option selected="selected" value="?">(select item)</option>
<option value="0">(0) No</option>
<option value="1">(1) Yes</option>
<option value="-">(-) Not assessed</option>
</select>
</div>
<div class="questionItem format">
<input name="answers[2].SetAnswer" type="hidden" value="?" />
<input name="answers[2].Answer" type="number" value="" />
</div>
<div class="questionItem format">
<input name="answers[3].SetAnswer" type="hidden" value="red" />
<input name="answers[3].Answer" type="number" value="red" />
</div>
我能想到的最好的,但不起作用的是这样的:
var answerColl = $(this).find(":input").filter(function () {
return /^answers\[\d+\]\.Answer$/.test(this.name);
});
// Make sure there is an 'Answer' input, if there isn't, that is because it is
// not displayed, so assume not unanswered
if (answerColl.length > 0) {
var answerElement = answerColl.first();
var answer = answerElement.value;
// First check to see if the answer is ?
if (answer == "?")
return true;
// Next check to see if the answer is empty, if so, must check the setAnswer.
// If the setAnswer is ^, then this is no unanswered, if it is ? it is unanswered.
if (!Boolean(answer)) {
var setAnswerElement = $(this).find(":input").filter(function () { return /^answers\[\d+\]\.SetAnswer$/.test(this.name); }).first();
var setAnswer = setAnswerElement.value;
if (setAnswer == "?")
return true;
}
}
return false;
问题在于:
var answerElement = answerColl.first();
var answer = answerElement.value;
当我在调试器中查看它时,answerElement 是一个 jQuery 对象,但 answer 始终为空。查看 answerElement 时,默认值是我正在寻找的值,即实际答案,但我无法弄清楚如何在代码中得到它。
有什么建议么?