通过JavaScript跟踪表单中的更改的最佳方式是什么?

编程入门 行业动态 更新时间:2024-10-28 06:26:43
本文介绍了通过JavaScript跟踪表单中的更改的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想通过JavaScript跟踪表单中输入的更改。我的意图是(但不限于)

  • 仅当某些内容发生变化时启用保存按钮
  • 提醒用户是否想关闭该页面并保存一些内容

想法?

解决方案

遍历所有输入元素,并在每个元素上放置 onchange 处理程序。当发生火灾时,请设置一个标志,让您知道表单已更改。一个基本的版本可以非常容易地设置,但是不会很聪明地认识到某人是否将输入从a改为b,然后回到a。如果发现这种情况很重要,那么它仍然是可能的,但需要做更多的工作。

以下是jQuery中的一个基本示例:

$(#myForm) .on(change,:input,function(){ //当某些东西发生变化时,可以做任何你需要做的事情 //在窗口中设置一个onExit函数 $('#saveButton')。show(); } );

I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to

  • enable "save" button only when something has changed
  • alert if the user wants to close the page and something is not saved

Ideas?

解决方案

Loop through all the input elements, and put an onchange handler on each. When that fires, set a flag which lets you know the form has changed. A basic version of that would be very easy to set up, but wouldn't be smart enough to recognize if someone changed an input from "a" to "b" and then back to "a". If it were important to catch that case, then it'd still be possible, but would take a bit more work.

Here's a basic example in jQuery:

$("#myForm") .on("change", ":input", function() { // do whatever you need to do when something's changed. // perhaps set up an onExit function on the window $('#saveButton').show(); }) ;

更多推荐

通过JavaScript跟踪表单中的更改的最佳方式是什么?

本文发布于:2023-10-12 02:36:32,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   方式   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!