您的位置:首页 > Web前端 > JQuery

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

2017-09-05 10:12 281 查看
在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方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: