简体   繁体   English

Ajax 返回的 html 似乎无法识别适用于它的 javascript 函数

[英]Ajax returned html doesn't seem to recognize javascript functions that apply to it

I am making ajax requests which return elements in a table.我正在发出返回表中元素的 ajax 请求。 That all works great and it displays properly.这一切都很好,并且显示正确。 However, I notice that any elements that are appended to the table that contain something like so但是,我注意到附加到表格中的任何元素都包含这样的内容

<div id="myId">Some Text</div>

will not be bound by previous javascript methods that bind to the myId method like so:不会被绑定到 myId 方法的以前的 javascript 方法绑定,如下所示:

$("#myID").click(function() { alert("HI!") };

It works well on anything loaded before ajax is called but if it's html populated by ajax then for some reason those tags don't realize that they should listening for clicks.它适用于在调用 ajax 之前加载的任何内容,但如果它是由 ajax 填充的 html,那么由于某种原因,这些标签没有意​​识到它们应该监听点击。

Anyone have any insight on this.任何人都对此有任何见解。 I'm using JQuery for what it's worth我正在使用 JQuery 来获得它的价值

Use live , like this:使用live ,像这样:

$("#myID").live('click', function() { alert("HI!"); });

live binds the handler for current and future elements; live绑定当前和未来元素的处理程序; click only does it for current ones. click仅适用于当前的。

Your problem comes from the fact that .click() only binds your handler to already existing elements that match the selector.您的问题来自这样一个事实,即.click()仅将您的处理程序绑定到与选择器匹配的现有元素。 You need to make use of .live() or .delegate() , which will bind your handler to elements that exist now, as well as in the future.您需要使用.live().delegate() ,它们会将您的处理程序绑定到现在以及将来存在的元素。 For simplicity, let's go with .live() :为简单起见,让我们使用.live()

$("#myID").live("click", function() {
  alert("Hi!"); 
});

"How does it work?" “它是如何工作的?” you might ask.你可能会问。 Well, .live() actually binds your handler to the specified event to document .好吧, .live()实际上将您的处理程序绑定到指定的事件到document It then watches for the specified event as it bubbles up the DOM.然后它会在 DOM 冒泡时监视指定的事件。 When it reaches document , it checks to see where the event originated, if it originated from an element matching your selector, your handler fires.当它到达document ,它会检查事件的起源位置,如果它起源于与您的选择器匹配的元素,您的处理程序就会触发。

.delegate() works in much the same fashion, except that it binds the handler to the element you specify to $() , and as a parameter, it takes a selector. .delegate()以几乎相同的方式工作,除了它将处理程序绑定到您指定给$()的元素,并且作为参数,它需要一个选择器。 It then watches for the event and when it bubbles up to the element specified in $() , it checks to see if the event originated from the element you specified as the first parameter, if it does, your handler fires.然后它监视事件,当它冒泡到$()指定的元素时,它会检查该事件是否源自您指定为第一个参数的元素,如果是,则触发处理程序。

实现此目的的另一种方法是将其更改为

$(document).on('click', '#myID', function() { });

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

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