0

I have the code below that is working fine but why is the jQuery returning $NaN when I run it via my wordpress theme using the format below:

jQuery:

jQuery(document).ready(function($) {

          var $span = $('.amount'),
        originalPrice = +$span.text().substr(1);

    $('.addon-select').change(function () {
        var price = +$(this).find('option:selected').data('price');
        $span.text('$' + (price + originalPrice));
    });


    });

Sample HTML:

<select class="addon addon-select" name="addon-artwork">

                <option value="">Select an option...</option>

                <option data-price="30.00" value="graphic-design-1" >Graphic Design (<span class="amount">&#36;30</span>)</option>
                <option data-price="0.00" value="artwork-provided-2" >Artwork provided</option>

</select>
<span class="amount">$39</span>
4

2 回答 2

3

NaN仅在<option>选择第一个时显示,因为它没有data-price属性。要么给它一个,要么为该选项添加一个特殊情况。

于 2013-08-16T02:24:37.497 回答
0

演示

NAN是否存在,因为您在选择第一个选项时data-price未定义。

检查所选项目的值是否不为空,而if (this.value !== '') {..}不是将价格添加到跨度。

and in the else part ie when the selected item value is ''than use$span.text('$' + originalPrice);

jQuery(document).ready(function ($) {

    var $span = $('.amount');
    var originalPrice = +$span.text().substr(1);
    $('.addon-select').change(function () {
        if (this.value !== '') {
            var price = +$(this).find('option:selected').data('price');
            $span.text('$' + (price + originalPrice));
        }else{
             $span.text('$' + originalPrice);
        }

    });
});
于 2013-08-16T02:26:57.210 回答