简体   繁体   English

如何重新加载页面时如何重置文本输入的值?

[英]How do I reset the value of a text input when the page reloads?

Firefox (and probably other browsers) want to keep whatever text the user entered in the text input, even after a reload. Firefox(可能还有其他浏览器)希望保留用户在文本输入中输入的任何文本,即使在重新加载后也是如此。 Just including the default text (that I want the input to revert to) in the html doesn't work: 只是在html中包含默认文本(我希望输入还原到)不起作用:

<input tyep='text' value='default text' />

And neither does trying to use JS 并且都没有尝试使用JS

window.onload = function() {document.getElementById("mytextinput").value = 'default text'}

You can use plain old HTML :) 你可以使用普通的旧HTML :)

Set autocomplete='off' in the attribute 在属性中设置autocomplete='off'

<input type='text' value='default text' autocomplete='off' />

This works on most modern browsers. 这适用于大多数现代浏览器。

Technically, you don't have to run a function onload to clear it--you could just put the javascript right in the page. 从技术上讲,您不必运行onload函数来清除它 - 您只需将javascript放在页面中即可。 For instance: 例如:

document.getElementById("mytextinput").value = ''

or with jQuery 或者使用jQuery

$("mytextinput").val('');

Note that it's always a good idea to work with a dom listener to ensure that your javascript fires after the dom has been properly built. 请注意,使用dom侦听器始终是一个好主意,以确保在dom正确构建后启动javascript。 So, in the example of jQuery, this would be as easy as 所以,在jQuery的例子中,这将是如此简单

$(document).ready(function() {
   $("mytextinput").val('');
});

Try this: 尝试这个:

<input type='text' id='mytextinput' value='default text' />
<script>
    document.getElementById("mytextinput").value = 'default text';
</script>

This code should run as soon as the textbox has loaded. 加载文本框后,此代码应立即运行。 The onload event can seem inconsistent, I'm not entirely sure how it behaves in multiple browsers on different actions like refreshing. onload事件似乎不一致,我不完全确定它在多个浏览器中如何在不同的操作(如刷新)上运行。

You can call the script differently, put it in a function, put it somewhere else etc, but it's good to start with a working version. 你可以用不同的方式调用脚本,把它放在一个函数中,把它放在其他地方等等,但是从一个工作版本开始是件好事。

If this doesn't work on other browsers there isn't much you can do because some browsers will try and be 'helpful' and always autofill for you. 如果这在其他浏览器上不起作用,那么您可以做的事情就不多了,因为有些浏览器会尝试“有用”并且总是为您自动填充。

I think you should do a server side coding on page reload. 我认为你应该在页面重新加载时进行服务器端编码。 Page reload is generally a postback type idea . 页面重新加载通常是一种回发类型的想法。 The page gets reloaded from server. 页面从服务器重新加载。 If you are doing asp.net , in page_load method add your default text. 如果您正在使用asp.net,请在page_load方法中添加您的默认文本。 :) :)

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

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