我们使用preventDefault方法时有用吗?

Aid*_*ell 2 javascript methods preventdefault

我们使用preventDefault方法时有用吗?(在函数的开头和结尾处).我看过的所有教程都在函数结尾处放置了preventDefault,但我认为你要做的第一件事是阻止默认行为.我注意到它可以工作,如果它在函数的开头,它在函数的最后工作:

function calculateResults(e){

    e.preventDefault();
    //UI Vars
    const amount = document.querySelector(`#amount`);
    const interest = document.querySelector(`#interest`);
    const years = document.querySelector(`#years`);
    const monthlyPayment = document.querySelector(`#monthly-payment`);
    const totalPayment = document.querySelector(`#total-payment`);
    const totalInterest =document.querySelector(`#total-interest`);

    const princapal =  parseFloat(amount.value);
    const calculatedInterest = parseFloat(interest.value)/100/12;
    const calculatedPayment = parseFloat(years.value) * 12;

    // compute monthly payments
    const x = Math.pow(1 + calculatedInterest, calculatedPayment);

}
Run Code Online (Sandbox Code Playgroud)

VS

function calculateResults(e){

    //UI Vars
    const amount = document.querySelector(`#amount`);
    const interest = document.querySelector(`#interest`);
    const years = document.querySelector(`#years`);
    const monthlyPayment = document.querySelector(`#monthly-payment`);
    const totalPayment = document.querySelector(`#total-payment`);
    const totalInterest =document.querySelector(`#total-interest`);

    const princapal =  parseFloat(amount.value);
    const calculatedInterest = parseFloat(interest.value)/100/12;
    const calculatedPayment = parseFloat(years.value) * 12;

    // compute monthly payments
    const x = Math.pow(1 + calculatedInterest, calculatedPayment);

    e.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)

我想我主要担心的是,如果我在函数中有很多事情,浏览器可能会在最终阻止默认之前执行其默认行为吗?或者它会在尝试执行默认行为之前等待函数中的所有内容吗?

cha*_*tfl 5

最佳做法是尽快调用它.

如果代码在到达之前抛出任何错误,preventDefault则可能无法调用它,浏览器将执行默认操作.

一旦调用它,如果在此之后抛出错误,则不会发生默认操作