我需要在data属性中找到最小值和最大值,但它返回0
这是我的代码
<div data-price="2" class="maindiv">test</div>
<div data-price="5" class="maindiv">test</div>
<div data-price="3" class="maindiv">test</div>
<div data-price="0" class="maindiv">test</div>
<div data-price="25" class="maindiv">test</div>
<div data-price="10" class="maindiv">test</div>
<script>
var ids = $("div[data-price]").map(function() {
return this.id;
}).get();
var highest = Math.max.apply( Math, ids );
var lowest = Math.min.apply( Math, ids );
alert(highest);
alert(lowest);
</script>
答案 0 :(得分:2)
您需要返回数据价格属性,而不是其ID
<script language="JavaScript">
var acct = "0";
</script>
<xsl:for-each select="acctdtls">
<xsl:if test="@codacctno != acct)">
<script language="JavaScript">
acct = "<xsl:value-of select = '@codacctno'/>";
</script>
</xsl:if>
</xsl:for-each>
var ids = $("div[data-price]").map(function() {
return $(this).attr("data-price");
}).get();
var highest = Math.max.apply( Math, ids );
var lowest = Math.min.apply( Math, ids );
alert(highest);
alert(lowest);
答案 1 :(得分:1)
您可以使用常规JavaScript执行此操作:
//Variable to hold our results
var data = [];
//Loop through HTML nodes
for (var i = 0; i < document.querySelectorAll(".maindiv").length; i++) {
data.push({
node : document.querySelectorAll(".maindiv")[i],
value : parseInt(document.querySelectorAll(".maindiv")[i].getAttribute("data-price"))
});
}
//Sort lowest to highest (Only use one sort! Pick either this or the next one as they overwrite each Other)
data = data.sort(function (a, b) {
return a.value - b.value;
});
//Sort highest to lowest (Only use one sort! Pick either this or the last one as they overwrite each Other)
data = data.sort(function (a, b) {
return b.value - a.value;
});
//List all
console.log(data);
//List first (highest or lowest depending or sort)
console.log('first', data[0].value);
//List last (highest or lowest depending or sort)
console.log('last', data[data.length-1].value);
&#13;
<div data-price="2" class="maindiv">test</div>
<div data-price="5" class="maindiv">test</div>
<div data-price="3" class="maindiv">test</div>
<div data-price="0" class="maindiv">test</div>
<div data-price="25" class="maindiv">test</div>
<div data-price="10" class="maindiv">test</div>
&#13;
答案 2 :(得分:0)
目前,您正在从 var newGuid = (function() {
var guid = parseInt(Math.random() * 36);
return function newGuid() {
return Date.now().toString(36) + (guid++ % 36).toString(36) + Math.random().toString(36).slice(2, 4);
};
})();
函数返回id属性。将其更改为map
data-price