【问题标题】:How can I display the highest number in an array with javascript or jquery?如何使用 javascript 或 jquery 显示数组中的最高数字?
【发布时间】:2017-04-27 01:13:09
【问题描述】:

在我的分数跟踪应用程序中,我试图在游戏进行时显示当前领导者的姓名 (#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;
};     

【问题讨论】:

标签: javascript dom-manipulation


【解决方案1】:

这是一个 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

【讨论】:

    猜你喜欢
    • 2021-02-09
    • 1970-01-01
    • 2011-12-09
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多