如何使用javascript或jquery在数组中显示最高数字?

时间:2016-12-12 07:52:09

标签: javascript dom-manipulation

在我的分数跟踪应用程序中,我试图在游戏继续时显示当前领导者的名称(#firstPlacePlayer)和分数(#firstPlaceScore)。我想只将h3的高得分值移到我的h2。我的HTML:

<h2><span id="firstPlacePlayer">Leader </span>has 
<span id="firstPlaceScore">0</span> points!</h2>

<h3><span class="p1Name">Ben</span>: <span id="p1Display">2</span> VPs</h3>
<h3><span class="p2Name">Dan</span>: <span id="p2Display">2</span> VPs</h3>

我的javascript:

var p1Name = document.querySelector('p1Name');
var playerScores = [p1Score, p2Score]
var firstPlace = Math.max.apply(null, playerScores);

function changeLeader () {
    document.getElementById('firstPlaceScore').textContent = firstPlace;
};     

1 个答案:

答案 0 :(得分:0)

这是一个jquery解决方案

var palyers = $("h3"),scores=[];
$.each(palyers, function(i,player){
  scores.push(parseInt($(player).find("SPAN:last")[0].textContent,10));
})
var firstPlace = Math.max.apply(null, scores);
changeLeader();
function changeLeader () {
    document.getElementById('firstPlaceScore').textContent = firstPlace;
}; 

这是一个有效的plnkr http://plnkr.co/edit/cBHOuHyrHz1Gk7zzYVX8?p=preview