문제

in my html I have the following:

<div class="boxS" data-catTotal="19"></div>
<div class="boxS" data-catTotal="12"></div>
<div class="boxS" data-catTotal="4"></div>
<div class="boxS" data-catTotal="8"></div>
<div class="boxS" data-catTotal="4"></div>
<div class="boxS" data-catTotal="1"></div>

And my JavaScript as follows:

var sizeBoxMax = null;
var sizeNew;
$(".boxS").each(function(){

    var sizeBox = $(this).attr("data-catTotal");
    alert($(this).attr("data-namez") + " " + sizeBox + " " + sizeBoxMax);

    if (sizeBox < sizeBoxMax) {
        sizeNew = (sizeBox / sizeBoxMax) * 100;
        sizeNew = Math.ceil(sizeNew.toFixed(0));
        $(this).attr("style", "width: " + sizeNew + "% !important");
    }

    else {
        if (sizeBoxMax == null) {
            sizeBoxMax = $(this).attr("data-catTotal");
        }
        // alert($(this).attr("data-namez") +" "+ sizeBox);
    }

});

The problem is that the if statement isn't being accessed, even when the sizeBoxMax is 19 the whole time. What happens is that 19, 12, and 1 are working right, but the rest are unaffected. Any ideas on what I could do? I tried to parseInt() but I just get NaN. Any help would be greatly appreciated! Thanks.

도움이 되었습니까?

해결책

Need to set sizeBoxMax inital value to an integer instead of null

You can see the result working in jsuna's fiddle when using a int value.

다른 팁

In addition to Christopher Marshall's Answer you should be using jQuery's Data() method.

var sizeBox = $(this).data("catTotal");

and

sizeBoxMax = $(this).data("catTotal");

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top