javascript 网页启动时无需点击按钮就运行代码

查看:77
本文介绍了javascript 网页启动时无需点击按钮就运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想实现如截图效果。 网页运行的时候,默认第一radio 按钮已选。 价格和总和同步更新。 加减按钮和求和都测试过没有问题,只差右图效果。 求大神指点。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>    
</head>
<body>    
    
<form action="lol.php" method="POST">    
<div id="input_div">
<input type="radio" name="hey" value="10" checked>$10<br>
<input type="radio" name="hey" value="20">$20<br>
<input type="radio" name="hey" value="30">$30<br><br>
price$<input type="text" id="it" value=""><br><br>

quantity<button type="button" id="moins" onclick="minus()">-</button>
<input type="number" name="wtf" value="1" id="count">
<button type="button" id="moins" onclick="plus()">+</button><br><br>

Total <input type="text" value="" id="total">

</div>
    
</form>

<script>
$(document).ready(function(){
$("input[type=radio]").click(function(){
   $("#it").val(this.value);
}); 
}); 

    var price = document.getElementById('it');
    var count = 1;
    var total =0;
    var countEl = document.getElementById("count");
    var countEl1 = document.getElementById("total");

    function plus(){
        count++;
        total=price.value*count;
        countEl.value = count;
        countEl1.value = total;
        
    }
    function minus(){
      if (count > 1) {
        count--;
        total=price.value*count;
        countEl.value = count;
        countEl1.value = total;
      }  
    }

</script>
</body>
</html>

解决方案

改成这样

var price = document.getElementById('it');
var count = 1;
var total = 0;
var countEl = document.getElementById('count');
var countEl1 = document.getElementById('total');

$(document).ready(function() {
    $('#it').val($('input[checked]').val());
    $('#total').val($('input[checked]').val());

    $('input[type=radio]').click(function() {
        $('#it').val(this.value);
        $('#total').val($('#it').val()* count);
    });
});

这篇关于javascript 网页启动时无需点击按钮就运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆