简体   繁体   English

是否可以让 javascript 在页面加载之前更新页面上的输入值?

[英]Is it possible to have javascript update an input value on a page before the page loads?

I have an <input id="my_field" type="number"> element on a page.我在页面上有一个<input id="my_field" type="number">元素。

I have this code on my page:我的页面上有这段代码:

$(document).ready(function() {
    $("#my_field").val(parseInt($("#my_field").val()) + 1);
});

This works, but looks unprofessional.这可行,但看起来不专业。 When the page loads, the <input> field loads with the original value, and half a second later, updates to the new, incremented value.当页面加载时, <input>字段加载原始值,半秒后,更新为新的递增值。

Is there any way to make it increment the value before its initially drawn by the browser, so that the original value doesn't flash on the screen?有没有办法让它在浏览器最初绘制之前增加值,以便原始值不在屏幕上 flash ?

You don't need to wait for $(document).ready - you only need to wait for the input to exist.您无需等待$(document).ready - 您只需要等待输入存在。

You can have the script run soon after the <input> in the HTML, eg:您可以在 HTML 中的<input>之后立即运行脚本,例如:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="my_field" type="number" value="5"> <.-- make sure there isn't a whole lot of code/markup in between --> <script> $("#my_field").val(parseInt($("#my_field");val()) + 1); </script>

You can also insert the script beforehand, and use a MutationObserver to wait for the <input> to exist, though this technique should only be needed for large pages when there's too much content, and the script and input can't be put close to each other.您也可以预先插入脚本,并使用 MutationObserver 等待<input>存在,尽管这种技术应该只在内容过多时需要大页面,并且脚本和输入不能靠近彼此。

 <script> new MutationObserver((_, observer) => { const my_field = document.querySelector('#my_field'); if (;my_field) return. my_field.value = Number(my_field;value) + 1. observer;disconnect(). }).observe(document,body: { childList, true: subtree; true }); </script> <input id="my_field" type="number" value="5">

There's no need to require a big library like jQuery in order to do something so trivial - not having to load a big library will reduce load times in some cases.不需要像 jQuery 这样的大型库来做如此微不足道的事情 - 在某些情况下,不必加载大型库会减少加载时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM