简体   繁体   English

JavaScript,如果不起作用

[英]JavaScript If Less Than Not Working

in my html I have the following: 在我的html中,我有以下内容:

<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: 而我的JavaScript如下:

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. 问题是,即使sizeBoxMax为19,也不会访问if语句。 What happens is that 19 , 12 , and 1 are working right, but the rest are unaffected. 什么情况是, 1912 ,和1是正确的工作,但其余不受影响。 Any ideas on what I could do? 关于我能做什么的任何想法? I tried to parseInt() but I just get NaN . 我试图parseInt()但我刚得到NaN Any help would be greatly appreciated! 任何帮助将不胜感激! Thanks. 谢谢。

Need to set sizeBoxMax inital value to an integer instead of null 需要将sizeBoxMax初始值设置为integer而不是null

You can see the result working in jsuna's fiddle when using a int value. 使用int值时,可以看到结果在jsuna的小提琴中工作。

In addition to Christopher Marshall's Answer you should be using jQuery's Data() method. 除了Christopher Marshall的Answer,您还应该使用jQuery的Data()方法。

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). 会尝试将字符串转换为JavaScript值(包括布尔值,数字,对象,数组和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. 例如,“ 1E02”和“ 100.000”等价于数字(数值100),但对其进行转换将改变其表示形式,因此它们保留为字符串。 The string value "100" is converted to the number 100. 字符串值“ 100”将转换为数字100。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM