2

.inArray()配列の「0」値をチェックしてからreturn false;、ゼロがある場合は関数を中断するために使用しています。

現在使用しているコードは次のとおりです。

$(document).ready(function() {

    $('#calc').click(function(e) {

        var drop = $(".drop"),
            c = [],
            g = [];

        //Push values into an array.
        drop.each(function() {
            var $t = $(this),
                cals = $t.val(),
                option = $(':selected', this),
                gly = parseFloat(option.attr('rel'));
            g.push(gly * 2);
            c.push(cals * 2);
        });

        var inthere = jQuery.inArray('0', c) > -1;

        //don't calculate if array is empty
        if (c.length === 0) {
            return false;
        }
        //don't calculate with a '0' value in array
        if (inthere == true) {
            return false;
        }

        //shouldn't display if you haven't added a dropdown OR if the dropdown stayed on the "Default" option
        alert('Passed');
    });

    $('#add').click(function() {
        $('#contain').append('<select class="drop"><option value="" rel="" data-default="true">Default</option><option value="1" rel="2">Option 1</option><option value="3" rel="4">Option 2</option></select>');
    });

});​

ユーザーがoption「デフォルト」オプションをそのままにしてcおくと、渡される値は0になります。ドロップダウンに追加していない限り、何らかの理由でコードが渡されます。

c配列に「0」がある場合、コードが続行されないようにするにはどうすればよいですか?

これがフィドルです

4

1 に答える 1

2

配列には文字列が一致していません。'0'番号が一致してい0ます。

http://jsfiddle.net/DUs8e/1/

var inthere = jQuery.inArray(0, c) > -1;
于 2012-10-09T15:38:17.013 に答える