处理多个onload事件javascript

时间:2016-08-12 18:08:50

标签: javascript events event-handling onload conflict

我遇到以下Javascript代码问题。我正在尝试从给定的数组对象生成一个选择。

在窗口加载时调用setRoutesList函数,在select的change事件中调用calculatePrice函数。如果已设置选项标签,如何调用calculatePrice

使用Javascript:

function route(origin, destination, price1, price2, price3, price4, val) {
    this.origin = origin;
    this.destination = destination;
    this.price1 = price1;
    this.price2 = price2;
    this.price3 = price3;
    this.price4 = price4;
    this.val = val;
    this.toString = function () {
        return this.origin + "  -  " + this.destination;
    }
}

var routes = new Array;

routes[0] = new route('Paris', 'Rome', 1, 50, 20, 10, 10);
routes[1] = new route('Milan', 'Madrid', 2, 20, 20, 10);
routes[2] = new route('Barcelona', 'Lisbon', 3, 50, 50, 10);

window.onload = function () {
    var selectroute = document.getElementById('basic-route');
    var pax = document.getElementById('pax');
    var out = document.getElementById('out');

    function setRoutesList() {

        for (i = 0; i < routes.length; i++) {
            opt = document.createElement("option");
            opt.innerHTML = routes[i].toString();
            opt.value = routes[i].val;
            selectroute.appendChild(opt);

            selectroute.addEventListener("change", calculatePrice());
        }    
    }

    window.addEventListener("load", setRoutesList());

    function calculatePrice() {
        alert("I ' m Working!!!");
    }   
}

HTML:

<select id="basic-route">

    </select>

    <select id="pax">

        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>

    </select>

<div id="out"></div>

JsFiddle Here

0 个答案:

没有答案