问题
I looked up the load method to find an alternative to php includes. I got the load to add html dynamically and it works. The one issue though is that function aren't working. I think it's either an order issue, structure issue or plain logic. Any help to get my functions to work in dynamically generated html would be greatly appreciated. Sample structure below.
$(document).ready(function () {
"use strict";
$("header").load("/_includes/header.html");
});
$(window).bind("load", function () {
"use strict";
$('.class').click(function () {
$('#id').slideToggle('fast');
});
});
回答1:
If you have .class
element defined inside header.html
then you need to use event delegation as below:
$(document).on('click','.class',function () {
$('#id').slideToggle('fast');
});
Event delegation should be used on controls which are added to
DOM
at later part or afterDOM
gets loaded.
UPDATE
When you attach event directly to element like below:
$('.element').click(function(){
....
});
or as below:
$('.element').on('click',function(){
....
});
those event will not get attached to the dynamically added elements or elements which are added after DOM
load. So you need to attach event
either to document
targeting particular element
in DOM as below:
$(document).on('click','.element',function(){
...
});
or to its parent which was loaded during page load. For Ex:
Say you have below structure:
<div class="somediv">
<!--Many other children elements here-->
</div>
Now you will add one more event either by append
or by load
or in any other possible ways and structure will become as below:
<div class="somediv">
<!--Many other children elements here-->
<button class="element">Click here<button> <!--This is dynamically added element -->
</div>
and now you can attach event to .somediv
instead of attaching to document
, since it was added during DOM
load and newly added element will be inside this .somediv
.
This will actually improve performance of code as you are explicitly telling
jquery
from where to start to search for the dynamically added.element
andjquery
can search it more faster instead of traversing fromdocument
So you can write it as below:
$('.somediv').on('click','.element',function(){
//^^^^parent div ^^^dynamically added element
//do anything here
});
回答2:
try this
$(document).ready(function () {
"use strict";
$("header").load("/_includes/header.html", function () {
$('.class').click(function () {
$('#id').slideToggle('fast');
});
});
});
回答3:
Use .live() for older jQuery versions
$( ".class" ).live( "click", function() {
$('#id').slideToggle('fast');
});
for older
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
来源:https://stackoverflow.com/questions/32354020/jquery-functions-inside-of-dynamically-generated-html-not-working