[英]Element not accesible in jQuery after $.load(content)
I use jQuery with the $.load()
function to include markup (from separate file) in my main html file, index.html
我在
$.load()
函数中使用jQuery在我的主html文件index.html
包含标记(来自单独的文件)
For example, I load contact.html
in: 例如,我在以下位置加载
contact.html
:
<div id="bloc_load"></div> in 'index.html'
That works correctly. 这工作正常。
The issue is, in contact.html
I have: 问题是,在
contact.html
我有:
<input type="button" id="button_of_contact">
This element is loaded in index.html
but I cannot access it with: 此元素在
index.html
加载,但我无法访问它:
$('#button_of_contact').click(function(){
alert('Click');
});
If I view the source code in index.html
after loading contact.html
, I see: 如果我在加载
contact.html
后查看index.html
的源代码,我会看到:
<div id="bloc_load"></div>
The div
is empty, so I think jQuery cannot access. div
是空的,所以我认为jQuery无法访问。 How can I resolve this issue? 我该如何解决这个问题?
You need jQuery .live()
or .on()
method to bind events to dynamically created html. 您需要jQuery
.live()
或.on()
方法将事件绑定到动态创建的html。
Choose .live()
or .on()
depending on the version of jQuery you are using. 根据您使用的jQuery版本选择
.live()
或.on()
。
.live() Available since jQuery 1.3.
.live()自jQuery 1.3起可用。 Attach an event handler for all elements which match the current selector, now and in the future.
为现在和将来与当前选择器匹配的所有元素附加事件处理程序。
.on() Available since jQuery 1.7.
.on()自jQuery 1.7起可用。 Attach an event handler function for one or more events to the selected elements.
将一个或多个事件的事件处理函数附加到所选元素。
Check out my sample and this jsFiddle Demonstration 看看我的样本和这个jsFiddle演示
... for jQuery.live() ...对于jQuery.live()
$('#button_of_contact').live("click", function(e) {
e.preventDefault();
// do something;
});
... for jQuery.on() ...对于jQuery.on()
$('#button_of_contact').on("click", function(e) {
e.preventDefault();
// do something;
});
jQuery Docs - As of jQuery 1.7, .delegate() has been superseded by the .on() method.
jQuery Docs - 从jQuery 1.7开始,.delegate()已被.on()方法取代。 For earlier versions, however, it remains the most effective means to use event delegation.
但是,对于早期版本,它仍然是使用事件委派的最有效方法。 More information on event binding and delegation is in the .on() method.
有关事件绑定和委派的更多信息,请参见.on()方法。
$("#button_of_contact").delegate("input", "click", function() {
e.preventDefault();
// do something;
});
Assuming the content is loaded : 假设内容已加载:
$("#bloc_load").on('click', '#button_of_contact', function() {
console.log('click');
});
You will have to check the console to see the altered code with the loaded content, just right clicking and view source won't show the added content. 您必须检查控制台以查看已加载内容的更改代码,只需右键单击并查看源将不会显示添加的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.