在 javascript 中,是否有 onCreate 这样的事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8045458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:05:57  来源:igfitidea点击:

in javascript, is there such an event as onCreate?

javascriptjqueryjavascript-events

提问by user965641

I'm working with an existing system set up by someone else (no longer here). In this system, clicking on the text within a special <span>will trigger a js function which will replace the text with an <input>field. The text which was there is assigned as the valueof the <input>element.

我正在使用由其他人(不再在这里)设置的现有系统。在这个系统中,点击一个特殊的文本<span>将触发一个 js 函数,它将用一个<input>字段替换文本。这是存在的文本被指定为value所述的<input>元件。

An onblurevent is assigned to this new <input>field. This calls a function which updates the data in the database via an AJAX call. As part of this action, the <input>field is replaced with the new value (same <span>contents), and the onclick event is re-assigned. In this way, you can click on the text, change it, click elsewhere, and it is automatically updated in the database. Then you can do it again as it sets up the original events dynamically with each update.

一个onblur事件被分配给这个新<input>字段。这将调用一个函数,该函数通过 AJAX 调用更新数据库中的数据。作为此操作的一部分,该<input>字段被替换为新值(相同的<span>内容),并重新分配 onclick 事件。这样,你可以点击文本,改变它,点击别处,它会在数据库中自动更新。然后您可以再次执行此操作,因为它会在每次更新时动态设置原始事件。

It is in-between the first event and the second that I want access to that <input>field. I want to add a jquery .datepicker()to it.

我想要访问该<input>字段是在第一个事件和第二个事件之间。我想给它添加一个 jquery .datepicker()

How would I go about calling .datepicker()on a dynamically-created element?

我将如何调用.datepicker()动态创建的元素?

回答by mrtsherman

No, there isn't an event similar to an onCreate. The closest you can find is jQuery's .live(). This allows you to bind an event to an element now or in the future. I also think it will probably solve your problem.

不,没有类似于 onCreate 的事件。您能找到的最接近的是 jQuery 的 .live()。这允许您现在或将来将事件绑定到元素。我也认为它可能会解决您的问题。

http://api.jquery.com/live/

http://api.jquery.com/live/

$('input').live('click', function() {
   $(this).datepicker();
});

As AutoSponge handily pointed out, live is deprecated as of jQuery 1.7. They suggest using on or delegate instead.

正如 AutoSponge 轻松指出的那样,从 jQuery 1.7 开始不推荐使用 live。他们建议改用 on 或 delegate。

http://api.jquery.com/on/

http://api.jquery.com/on/

http://api.jquery.com/delegate/

http://api.jquery.com/delegate/