使两个脚本一起为下拉菜单工作

making two scripts work together for a dropdown menu

本文关键字:一起 下拉菜单 工作 脚本 两个      更新时间:2023-09-26

我有这个HTML代码

<html>
<head>
<script type="text/javascript">
    window.onload = function(){
    document.getElementById("shipping-method").onchange = function(){
        window.scrollTo(0, 0);
    };
};
</script>
<script>
function calc() {
var subtotal = parseFloat(document.getElementById("subtotal").innerHTML.substring(1));
var shipping = parseInt(document.getElementById("shipping-method").value);
if(shipping == 1) {
    var total = subtotal+6.95;
    document.getElementById("shipping").innerHTML = "$"+6.95;
} else {
    var total = subtotal+17.95;
    document.getElementById("shipping").innerHTML = "$"+17.95;
}
document.getElementById("total").innerHTML = "$"+total;
}
</script>
</head>
<body>
<select  onchange="calc()" class="shipping-method" id="shipping-method">
<option value="">-Choose a shipping method-</option>
<option selected="selected" value="1">normal shipping - $6.95</option>
<option value="2">Priority Shipping - $17.95</option>
</select>
<div class="calculations">
<table>
<tbody><tr>
    <td>Subtotal:</td>
    <td id="subtotal">$97.00</td>
</tr>

<tr>
    <td>Shipping:</td>
    <td id="shipping">$6.95</td>
</tr>

<tr class="total">
    <td>Total:</td>
    <td id="total">$103.95</td>
</tr>
</tbody></table>
</div>
</body>
</html>

下拉菜单是在一个网页的底部,所以我使用第一个脚本让用户在选择其中一个选项并获得总数后页面的顶部,但两个脚本不一起工作,我必须删除其中一个为另一个工作,如何使两个脚本一起工作没有任何冲突,谢谢。

您正在重写onchange函数。如果你想做两件事,那么把它们都放在onchange函数中,不要给它赋值两次。

下面是一些示例代码(为简洁而缩短)。

<html>
<head><title>Example</title></head>
<body>
<select id="shipping-method"></select>
<table></table>
<script type="text/javascript">
    function calc() {
        // do calculations here
    }
    document.getElementById("shipping-method").onchange = function(){
        window.scrollTo(0, 0); // scroll to top
        calc(); // call function
    };
</script>
</body>
</html>

请注意,我把javascript放在底部,以避免访问不存在的元素

试试:

function calc() {
var subtotal = parseFloat(document.getElementById("subtotal").innerHTML.substring(1));
var shipping = parseInt(document.getElementById("shipping-method").value);
if(shipping == 1) {
    var total = subtotal+6.95;
    document.getElementById("shipping").innerHTML = "$"+6.95;
} else {
    var total = subtotal+17.95;
    document.getElementById("shipping").innerHTML = "$"+17.95;
}
document.getElementById("total").innerHTML = "$"+total;
}

就在函数的顶部:

window.onload = function(){
document.getElementById("shipping-method").onchange = function(){
    window.scrollTo(0, 0);
};