[英]making two scripts work together for a dropdown menu
我有這個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>
下拉菜單位於網頁的底部,因此我使用第一個腳本在選擇了一個選項並獲得了總計之后將用戶帶到頁面頂部,但是兩個腳本無法一起使用,我有要刪除其中一個以便另一個工作,如何使兩個腳本一起工作而沒有任何沖突,謝謝。
嘗試堅持一下:
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);
};
您將覆蓋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放在底部,以避免訪問不存在的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.