页面加载后自动执行.on()函数 [英] Execute .on() function automatically after page load

查看:347
本文介绍了页面加载后自动执行.on()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用$("#container").on("click", contentEffects);使ajax调用后一些jquery代码再次工作.但是,我希望.on()函数可以在页面加载后立即自动执行,并且没有click事件.有可能吗?

I use $("#container").on("click", contentEffects); to make some jquery code work again after ajax call. However, I hope the .on() function can be executed immediately and automatically after page load, and without the click event. Is that possible?

请查看我的网站和javascript文件:

Please take a look at my site and the javascript file:

http://peters-playground.com/blog.html

https://github. com/P233/p233.github.com/blob/master/js/script.js#L30-L78

当ajax加载新帖子时,我必须单击帖子内容以启用javascript,并且还需要单击两次按钮以使其起作用.真烦人.我该如何避免这个问题?

When new post is loaded by ajax, I have to click on the post content to enable javascript and I also need to click button twice to make it work. That is really annoying. How can I avoid this problem?

谢谢!

推荐答案

您可以在链中运行它:

// Anonymouse function passed into $ will be invoked
// When the document has loaded
$(function () {

    // Immediately after binding the click handler
    // We invoke the click event on #container
    $("#container").on("click", contentEffects).click();

});

听起来似乎应该考虑的是 event-delegation ,并将事件绑定到页面加载时出现的最近的静态祖先元素.例如,假设我们有一个由AJAX动态填充的项目列表:

What is sounds like you should consider though is event-delegation, and binding events to the nearest static ancestor element that is present when the page loads. For instance, suppose we have a list of items populated dynamically by AJAX:

<ul id="items">
    <li>First item on load.</li>
    <!-- More items will be loaded
         via AJAX later on --->
</ul>

您可能希望列表项在单击时执行某些操作,因此您可能会将处理程序绑定到其click事件:

You might want the list items to do something when you click on them, so you would probably bind handler to their click event:

$("#items li").on("click", function () {
    alert( $(this).html() );
});

此功能适用于页面上已存在的所有列表项,但是随着您的体验,新项将不再受此限制,因此在AJAX之后,您必须重新绑定它所有新的列表项.

This works for any list items already on the page, but as you are experiencing, new items won't have this bound to them, so after your AJAX you will have to re-bind it to all new list items.

我们可以绑定到始终存在的ul元素,而不是这样做,并且只需侦听源自li元素的事件即可:

Instead of doing this, we can bind to the ul element, which is always present, and simply listen for events that originated from li elements:

$("#items").on("click", "li", function () {
    alert( $(this).html() );
});

现在我们的事件不再需要重新绑定,因为#items随页面一起加载,并且再也不会移到任何地方.嵌套列表项(无论是否通过AJAX加载)中冒泡到该元素的任何click事件都将被捕获并处理.

Now our event never needs to be re-bound, since #items is loaded with the page, and never goes anywhere. Any click event that bubbles up to this element from a nested list item (whether it was loaded via AJAX or not) will be captured and handled.

这篇关于页面加载后自动执行.on()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆