简体   繁体   English

有没有办法对通过jQuery .load()加载的动态HTML进行全局事件绑定?

[英]Is there a way to do global event binding on dynamic HTML loaded via jQuery .load()?

I have an HTML page that uses jQuery .load() to pull in HTML from other files. 我有一个使用jQuery .load()从其他文件中提取HTML的HTML页面。 I do this mostly for readability purposes. 我这样做主要是出于可读性目的。

I ran into a problem whereby code that is loaded via .load() is not "visible" to other javascript loaded later in the module because .load() is asynchronous. 我遇到了一个问题,即由于.load()是异步的,因此通过.load()加载的代码对于以后在模块中加载的其他javascript不“可见”。 This was solved in another StackOverflow question of mine with very good results, by doing the .click() binding in the .load() callback. 通过在.load()回调中执行.click()绑定,在我的另一个StackOverflow问题中解决了这一问题,并取得了很好的结果。 SO shone through like it always does! 照常照做!

Now, I have another question that is also related. 现在,我还有另一个与此相关的问题。

HTML: HTML:

        <div class="mainContent" style="color:white; overflow-y: auto; position:fixed; top:210px; bottom:60px;">
            <div class="linkContent" id="contentAboutUs"        style="display:none"></div>
            <div class="linkContent" id="contentAboutUsCompany" style="display:none"></div>
            <div class="linkContent" id="contentAboutUsVerify"  style="display:none"></div>
            <div class="linkContent" id="contentAboutUsSelf"    style="display:none"></div>
            <div class="linkContent" id="contentAboutUsHow"     style="display:none"></div>
        </div>

jQuery ready() function: jQuery ready()函数:

$("#contentAboutUs").load("contentAboutUs.html");
$("#contentAboutUsCompany").load("contentAboutUsCompany.html");
$("#contentAboutUsVerify").load("contentAboutUsVerify.html");
$("#contentAboutUsSelf").load("contentAboutUsSelf.html", function () { $(".saveButton").click(function () { saveForm(); })  });
$("#contentAboutUsHow").load("contentAboutUsHow.html");

You will notice that on the AboutUsSelf .load(), a callback binds the click event of the ".saveButton" to a function called saveForm(). 您将注意到,在AboutUsSelf .load()上,回调将“ .saveButton”的click事件绑定到名为saveForm()的函数。 This works perfectly, and was the answer I got from my previous SO question. 这非常有效,这是我从上一个SO问题得到的答案。

As you see, ".saveButton" is a class, and in fact, this button will be on MANY pages of the form; 如您所见,“。saveButton”是一个类,实际上,此按钮将在表单的许多页面上; which is why it is a class and not an ID. 这就是为什么它是类而不是ID的原因。

The question then is this: I do not want to do this click() binding on every section that contains one of these buttons. 然后的问题是:我不想在包含这些按钮之一的每个部分上执行click()绑定。 Is there a way to dynamically .load() this HTML, and yet apply this click() binding globally instead of doing it in the .load() callback individually in every case where it is needed? 有没有一种方法可以动态地对该HTML进行.load(),然后全局应用此click()绑定,而不是在每种需要的情况下单独在.load()回调中单独进行处理?

Since you are loading these inside a container, you can use that. 由于您是将它们加载到容器中,因此可以使用它。

$('.mainContent').on('click','.saveButton', function(){
     saveForm();
});

Event handlers bound this way bind to the container and it "looks within" for the selector of the button. 用这种方式绑定的事件处理程序绑定到容器,并且它在“内部”寻找按钮的选择器。 You cannot directly bind to the class for the button as it has nothing to bind to until it is loaded and in the DOM. 您无法直接绑定到该按钮的类,因为在将其加载到DOM中之前,没有任何可绑定的类。

Bind to the closest container (not document for instance) that you can to avoid the deep "look within" impact with a super large DOM. 绑定到最近的容器(例如,不是文档),您可以避免使用超大型DOM产生深层的“内部查看”影响。

Note that one thing you also experience here is multiple hits to your sever - ie you would benefit from the cache of the HTML if it were in the page already and it only hits the page once that way. 请注意,您在这里还遇到的一件事是服务器多次命中-即,如果HTML缓存已经存在于页面中,并且仅以这种方式命中一次,您将从中受益。 That being said, dynamic page portions are a good candidate for this type binding at the container level. 就是说,动态页面部分是在容器级别进行此类型绑定的很好的候选者。

With ASP.NET MVC for instance these can be put in partial views and get in the page prior to hitting the browser. 例如,使用ASP.NET MVC,可以将它们放在部分视图中,并在进入浏览器之前进入页面。

You did not ask but I would also move the style to a CSS file and not put it in the markup - this then makes your markup much cleaner and easier to modify. 您没有要求,但是我也将样式移动到CSS文件中,而不是将其放入标记中-这样可以使标记更整洁,更容易修改。

看看ajaxComplete-应该能够在其中附加click事件并将其应用于加载的所有新按钮

I believe what you are looking for is event delegation . 我相信您正在寻找的是事件委托

Essentially, what you can do is bind your event listener, using on() , to a containing element instead of directly on the element you're listening to. 本质上,您可以做的是使用on()将事件监听器绑定到一个包含元素,而不是直接在您正在监听的元素上。 Relevant info: 相关信息:

If we were to click our newly added item, nothing would happen. 如果我们单击新添加的项目,则不会发生任何事情。 This is because of the directly bound event handler that we attached previously. 这是因为我们之前附加了直接绑定的事件处理程序。 Direct events are only attached to elements at the time the .on() method is called. 直接事件仅在调用.on()方法时附加到元素。 In this case, since our new anchor did not exist when .on() was called, it does not get the event handler. 在这种情况下,由于在调用.on()时我们的新锚点不存在,因此它不会获取事件处理程序。

Example: 例:

$("#container-of-some-sort").on("click", ".saveButton", function(){ 
    saveForm(); 
});

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

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