如何在页面加载时初始化keyup函数

时间:2015-05-01 11:00:10

标签: javascript jquery

我有以下

var sel = window.getSelection();
var range = sel.getRangeAt(0);

我想在页面加载时调用keyup函数,以便在计算中运行一些默认值,因为价格最初从空开始。

我可以这样做吗?

$(document).ready(function () {
    //window.onload = LabourPrice;

    //Control Proofing Time and LabourCost
    $('#ArtworkDetail_NoOfProofs').keyup(function () {
        function LabourPrice() {
            var time = "@Model.ArtworkDetail.ProofType.DefaultProofTime".split(':');
            var seconds = (+time[0]) * 60 * 60 + (+time[1]) * 60 + (+time[2]);
            var newSeconds = seconds * $('#ArtworkDetail_NoOfProofs').val();

            var date = new Date(newSeconds * 1000);
            var hh = date.getUTCHours();
            var mm = date.getUTCMinutes();
            var ss = date.getSeconds();

            var hourlyLabour = $('#LabourCostCentrePrice').val();
            hourlyLabour = hourlyLabour.split('£');
            var costPerSecond = hourlyLabour[1] / 3600;
            var calculateCost = costPerSecond * newSeconds;
            //alert("£"+calculateCost.toFixed(2));
            $('#ArtworkDetail_ProofingLabourCost').val("£" + calculateCost.toFixed(2));

            // If building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
            if (hh > 12) { hh = hh % 12; }
            // Ensure each element has two-digits
            if (hh < 10) { hh = "0" + hh; }
            if (mm < 10) { mm = "0" + mm; }
            if (ss < 10) { ss = "0" + ss; }
            // Format your to HH:MM:SS
            var t = hh + ":" + mm + ":" + ss;
            $('#ArtworkDetail_ProofType_DefaultProofTime').val(t);
        }
        });

});

然后我将如何包装LabourPrice?

由于

修改

按要求添加了功能细节

2 个答案:

答案 0 :(得分:2)

我认为window.onload是多余的,因为它是ready的一部分,并且需要在ready函数内设置事件。为什么不试试

$(document).ready(function () {
    $('#ArtworkDetail_NoOfProofs').keyup(function () {
    });
    LabourPrice();
}
function LabourPrice() {
}

假设LabourPrice是一个函数(刚看到你的编辑)。此函数定义可以超出ready

答案 1 :(得分:2)

LabourPrice应该在keyup事件之外。正如你现在所知,LabourPrice仅存在于keyup事件中,但你想从keyup事件中调用它:

$(window).load(function(){
  $('#ArtworkDetail_NoOfProofs').keyup(function () {
    LabourPrice();
  }
}

function LabourPrice(){ ... }

Here's a good source关于window.load与document.ready的不同之处,尽管这不是你的主要问题。