在jQuery方法中能调用JS方法吗?

来源:互联网 发布:kindle推送软件 编辑:程序博客网 时间:2024/06/04 18:58

在jQuery方法中能调用JS方法吗?

能,在jQuery方法中直接写入要调用已写好的方法名()即可。

在项目中,有多个地方用到结账的功能。
比如,
点击结账按钮,由JS获取对应行列的数据,进行计算并显示到页面,
点击改变数量按钮,由JS获取新的数据重新计算并显示,
点击移除按钮,又会用到上述JS方法。
这样导致JS文件中的代码行太多,而且都是重复的代码。
这时候,需要将上述重复用到的地方提取出来,写成一个方法。
让需要用到结算的地方去调用就可以了。
这里写了一个名为getResult的function.

function getResult() {    var $input = $("input[class=count]");    var $booktd = $("td[class=bookPrice]");    var $disptd = $("td[class=disPrice]");    var inputCount = $input.length;    var bookPriceTotal = 0.00;    var disPriceTotal = 0.00;    var booksCount = 0;    for (var i = 0; i < inputCount; i++) {        var bookCount = $input.eq(i).val();        var bookPrice = $booktd.eq(i).text();        var disPrice = $disptd.eq(i).text();        booksCount = booksCount + parseInt(bookCount);        bookPriceTotal = bookPriceTotal + parseInt(bookCount) * bookPrice;        disPriceTotal = disPriceTotal + bookCount * disPrice    }    var $totalMoney = $("td[class=totalMoney]");    var $bookCount = $("td[class=bookCount]");    var $saveMoney = $("span[class=saveMoney]");    $totalMoney.text(disPriceTotal.toFixed(2) + " 元");    $bookCount.text(booksCount + " 本");    $saveMoney.text((bookPriceTotal - disPriceTotal).toFixed(2) + " 元");}

在用到它的地方,可以直接调用名字()

//点击确定按钮时$(function() {    $("button[class=confirmBtn]").click(function() {        getResult();      });})
//点击移除某项时$(function() {    $("button[class='removesBtn']").click(function() {        $("input[name='select']:checked").each(function() {            n = $(this).parents("tr").index();            $("table#myTable3").find("tr:eq(" + n + ")").remove();        });        getResult();    });    $("input[name='select']").attr("checked", false);});

。。。。
都是在 jQuery中调用了JS方法。

原创粉丝点击