简体   繁体   English

jQuery在加载时不触发(不是Ajax)

[英]jQuery on load not firing (not Ajax)

At the outset, let me be clear I'm not trying to use load() in an Ajax context to load a remote resource. 首先,让我清楚一点,我不是要在Ajax上下文中使用load()来加载远程资源。

I'm just trying to bind a function to an object that doesn't exist at page load time, such that I can do stuff to it when it does appear. 我只是想将一个函数绑定到在页面加载时不存在的对象,以便在出现时可以对其进行处理。 I'm using jQuery 1.7 我正在使用jQuery 1.7

I have a form with class="contact-form"). 我有一个带有class =“ contact-form”的表单。 This form is created on the fly, so it doesn't exist when document.ready() fires. 该表单是动态创建的,因此在document.ready()触发时不存在。

What I want to do is make some stuff happen when the form is created. 我要做的是在创建表单时使某些事情发生。 Presumably there should be a "load" or "ready" or some such event fired when the thing is available. 大概应该有一个“负载”或“就绪”,或在事物可用时触发此类事件。 Under previous versions of jQuery I'd have used delegate() or live(); 在早期版本的jQuery中,我将使用委托()或live();。 but these have been deprecated, and the current documentation says to use on( "load", handler ) or its shortcut, load(). 但是这些功能已被弃用,并且当前文档说要使用on(“ load”,handler)或其快捷方式load()。 I'm getting this from https://api.jquery.com/load-event/ . 我从https://api.jquery.com/load-event/获得此信息。

All of the following have so far failed to work: 到目前为止,以下所有方法均无效:

 $(".contact-form").load(function(){
    console.log("Hi there!");
  }); 

and

 $(".contact-form").on("load", function(){
    console.log("Hi there!");
  }); 

and, in a hail-mary based on ideas from Jquery event handler not working on dynamic content , 并且,在基于Jquery事件处理程序的思想而无法处理动态内容的冰雹玛丽中,

 $(document.body).on("load", ".contact-form", function(){
    console.log("Hi there!");
  });      

Any pointers appreciated. 任何指针表示赞赏。

Why do you need an event at all? 为什么根本需要一个活动? If the form is being added dynamically then run what you need to at the time 如果表单是动态添加的,则运行您当时需要的内容

var form = '<form class="contact-form"></form>';
$('body').append(form);
console.log("Hi there!");

This method is a shortcut for .on( "load", handler ). 此方法是.on(“ load”,handler)的快捷方式。

The load event is sent to an element when it and all sub-elements have been completely loaded. 当加载事件和所有子元素都已完全加载时,会将加载事件发送到该元素。 This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object. 该事件可以发送到与URL关联的任何元素:图像,脚本,框架,iframe和window对象。

For example, consider a page with a simple image: 例如,考虑一个带有简单图像的页面:

<img src="book.png" alt="Book" id="book">

The event handler can be bound to the image: 事件处理程序可以绑定到图像:

$( "#book" ).load(function() {
  // Handler for .load() called.
});

As soon as the image has been loaded, the handler is called. 加载图像后,立即调用处理程序。

Now put that inside a ready handler 现在将其放入准备好的处理程序中

$( document ).ready(function() {
  // onload functions here
});

If you use .load() which is a shortcut for .on('load') called the load event , the matching element ( form in this case) must exist at the time the page was loaded. 如果使用.load()作为.on('load')的快捷方式.on('load')称为load event ,则匹配的元素(在这种情况下为form )在页面加载时必须存在。 jQuery < 1.7 had a .live() function which would listen for new elements dynamically added to the page, but it was removed in jQuery 1.7 for various reasons, performance being a major one. jQuery <1.7具有.live()函数,该函数可以侦听动态添加到页面中的新元素,但是由于各种原因,它在jQuery 1.7中已被删除,性能是主要原因。

Other options 其他选择

jQuery LiveQuery is a plugin that sounds like it will do exactly what you're looking for. jQuery LiveQuery是一个插件,听起来像它会完全满足您的需求。 https://github.com/brandonaaron/livequery https://github.com/brandonaaron/livequery

jQuery Entwine will watch for new DOM elements using livequery, but also allows you to create DOM elements and use them as full objects with their own methods defined. jQuery Entwine将使用livequery监视新的DOM元素,但还允许您创建DOM元素并将它们用作定义了自己方法的完整对象。 https://github.com/hafriedlander/jquery.entwine https://github.com/hafriedlander/jquery.entwine

More info from jQuery's .on() docs jQuery的.on()文档的更多信息

You can use Delegated events to create a click handler which will fire when an element is dynamically added to your original selector (typically a container), such as: 您可以使用Delegated events创建单击处理程序,当将元素动态添加到原始选择器(通常是容器)时,该处理程序将触发,例如:

$( "#dataTable tbody" ).on( "click", "tr", function() {
  alert( $( this ).text() );
});

Now, when a new <tr> is added dynamically, it will have the click handler bound to it. 现在,当动态添加新的<tr> ,它将绑定click处理程序。 However, there is no event for the actual loading of an element into the DOM. 但是,没有将元素实际加载到DOM中的事件。

Event handlers are bound only to the currently selected elements; 事件处理程序仅绑定到当前选定的元素; they must exist on the page at the time your code makes the call to .on(). 当您的代码调用.on()时,它们必须存在于页面上。 To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. 为了确保元素存在并可以选择,请在文档就绪处理程序内对页面上HTML标记中的元素执行事件绑定。 If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. 如果将新HTML注入到页面中,请在将新HTML放入页面后选择元素并附加事件处理程序。 Or, use delegated events to attach an event handler, as described next. 或者,使用委托事件来附加事件处理程序,如下所述。

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. 委派事件的优势在于,它们可以处理来自后代元素的事件,这些事件在以后的时间添加到文档中。 By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. 通过选择保证在附加委托事件处理程序时会出现的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要。 This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. 例如,如果事件处理程序想要监视文档中的所有冒泡事件,则此元素可以是Model-View-Controller设计中视图的容器元素,也可以是文档。 The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready. 在加载任何其他HTML之前,document元素位于文档的开头,因此可以在其中附加事件,而不必等待文档准备就绪。

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

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