JavaScript代码中的计算器

时间:2014-04-09 13:30:50

标签: javascript html calculator

我为我的网站构建了一个简单的计算器,但是我的javascript代码存在问题而且我没有识别它。在jsfiddle工作正常,但当我放入空白的HTML页面时,代码不起作用。

这是Fiddle

var data = {
    "0": ["Please choose from above"],
        "20": ["Pachet 360$_0", "Pachet 900$_28", "Pachet 1800$_80", "Pachet 3600$_180", "Pachet 9000$_500", "Pachet 18000$_1020"],
        "15": ["Pachet free_0", "Pachet 400$_10", "Pachet 899$_45", "Pachet 1599$_85", "Pachet 2999$_185", "Pachet 5999$_385"],
        "10": ["Pachet 402.5$_10", "Pachet 1725$_80", "Pachet 8625$_480"]
}

 $("#one").change(function () {
    var first = $(this),
        second = $("#two"),
        key = first.val(),
        // instead of the original switch code
        vals = data[key] == undefined ? data.base : data[key],
        html = [];

        $.each(vals, function (i, val) {
            var v = val.split('_');
            html.push('<option value="' + v[1] + '">' + v[0] + '</option>')
        });
    second.html(html.join());
});

$("#one,#two").change(function () {
    var val1 = parseInt($('#one').val()) || 0,
        val2 = parseInt($('#two').val()) || 0;
    $('#total').text(val1 + val2)
    $('#total2').text((val1 + val2)*52)
})

2 个答案:

答案 0 :(得分:1)

您需要将jquery库包含在空白HTML页面中

<script src="//code.jquery.com/jquery-1.4.3.min.js"></script>

您需要在$(document).ready()函数中包装jquery代码。

// arrays instead of comma separated list and added base key
var data = {
    "0": ["Please choose from above"],
        "20": ["Pachet 360$_0", "Pachet 900$_28", "Pachet 1800$_80", "Pachet 3600$_180", "Pachet 9000$_500", "Pachet 18000$_1020"],
        "15": ["Pachet free_0", "Pachet 400$_10", "Pachet 899$_45", "Pachet 1599$_85", "Pachet 2999$_185", "Pachet 5999$_385"],
        "10": ["Pachet 402.5$_10", "Pachet 1725$_80", "Pachet 8625$_480"]
}

$(document).ready(function() {
    $("#one").change(function () {
        var first = $(this),
            second = $("#two"),
            key = first.val(),
            // instead of the original switch code
            vals = data[key] == undefined ? data.base : data[key],
            html = [];
        // create insert html before adding
        $.each(vals, function (i, val) {
            var v = val.split('_');
            html.push('<option value="' + v[1] + '">' + v[0] + '</option>')
        });
        // no need to empty the element before adding the new content
        second.html(html.join());
    });

    $("#one,#two").change(function () {
        var val1 = parseInt($('#one').val()) || 0,
            val2 = parseInt($('#two').val()) || 0;
        $('#total').text(val1 + val2)
        $('#total2').text((val1 + val2)*52)
    })

});

答案 1 :(得分:0)

在您的网站中,您甚至在加载DOM之前就调用了JavaScript函数,因此没有任何功能被分配给任何元素,因为它们在分配时不存在。

要么在关闭<body>标签之前定义脚本,要么使用document.ready wrapper。

$(document).ready(function() {
   //Your Code
});