我尝试获取具有最大NumVotes值的“值”字符串。 之后,我想做简单的断言(我知道该怎么做),但是我在获取此“值”时遇到了问题。我对此没有想法和知识。
<script>
var templates = [
@foreach ($templates->pluck('id', 'html')->toArray() as $k => $v)
'{{ $v }}',
@endforeach
];
$(document).ready(function(){
$('#templates').on('change', function (e) {
var valueSelected = this.value;
console.log(templates[valueSelected]);
});
});
</script>
<div class="input-select">
{!! Form::select('templates', $templates->pluck('html', 'id')->toArray(), null, ['class' => 'form-control', 'id' => 'templates', 'placeholder' => 'Select a template']) !!}
</div>
当前输出:
public class DomParserDemo {
public static void main(String[] args) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader("<poll name=\"language_dependence\" title=\"Language Dependence\" totalvotes=\"170\"><results><result level=\"1\" value=\"No necessary in-game text\" numvotes=\"168\"/><result level=\"2\" value=\"Some necessary text - easily memorized or small crib sheet\" numvotes=\"0\"/><result level=\"3\" value=\"Moderate in-game text - needs crib sheet or paste ups\" numvotes=\"0\"/><result level=\"4\" value=\"Extensive use of text - massive conversion needed to be playable\" numvotes=\"0\"/><result level=\"5\" value=\"Unplayable in another language\" numvotes=\"2\"/></results></poll>"));
Document doc = dbBuilder.parse(is);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("result");
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
System.out.println("Level = "+ element.getAttribute("level")+", "+
"Value = "+element.getAttribute("value")+", "+
"NumVotes = "+element.getAttribute("numvotes"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您已经在迭代所有元素。仅通过使用变量跟踪到目前为止的最大值并将其与每个值进行比较,即可通过元素属性之一找到最大值。您的for循环已被修改:
String targetValue = "";
int maxNumVotes = 0;
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
int numVotes = Integer.parseInt(element.getAttribute("numvotes"));
if (numVotes > maxNumVotes) {
maxNumVotes = numVotes;
targetValue = element.getAttribute("value");
}
}
System.out.println("Value: " + targetValue + " NumVotes: " + maxNumVotes);
但是,如果要按投票数对元素进行排序,请将元素添加到列表中,并使用比较器按投票数或任何其他字段进行排序。