最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Loading HTML into <div> with jQuery-ajax - Stack Overflow

programmeradmin4浏览0评论

I ran into a bit of trouble while trying to load an external HTML page into a div using jQuery-ajax. I had this div: <div id="content"></div> and wanted to fill it with $("#content").load("include/add.html"); It loads the HTML file perfectly, but inside that add.html is a button that should load add2.html(also using .load), but it seems that neither the button nor the datepicker in that file work. I'm guessing the .load function is responsible for that?

This is the content of add2.html:

<p>Nr: <input type="text"></input></p>
<p>Name: <input type="text"></input></p>
<p>Date: <input type="text" id="datepicker"></input></p>
<a href="#" id="button1">Next</a>

Please help, I'm desperate :D

I ran into a bit of trouble while trying to load an external HTML page into a div using jQuery-ajax. I had this div: <div id="content"></div> and wanted to fill it with $("#content").load("include/add.html"); It loads the HTML file perfectly, but inside that add.html is a button that should load add2.html(also using .load), but it seems that neither the button nor the datepicker in that file work. I'm guessing the .load function is responsible for that?

This is the content of add2.html:

<p>Nr: <input type="text"></input></p>
<p>Name: <input type="text"></input></p>
<p>Date: <input type="text" id="datepicker"></input></p>
<a href="#" id="button1">Next</a>

Please help, I'm desperate :D

Share Improve this question asked Mar 29, 2010 at 12:50 ehehhhehehhh 1,0743 gold badges16 silver badges27 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

As the file is included to the page after the events are bound, the events do not apply to the elements in 'add.html'. You need to bind the events again or use .on() method. In the case of the datepicker, it's easier to go with the first approach:

$("#content").load("include/add.html", function() {
    // Apply datepicker to elements in 'add.html'
    $('#content .date').datepicker();
});

For the button in add.html, you can use delegation:

$(document).on('click', '#content .button_in_add', function() {
    alert("I work even when included dynamically!");
    $('#content').load('include/add2.html');
});

Note that .on() bins does not go inside the .load() callback as the datepicker part did. If you have any elements in 'add2.html', you need to repeat the same steps for that also.

发布评论

评论列表(0)

  1. 暂无评论