Home  >  Article  >  Web Front-end  >  Using the same HTML fragment code on multiple pages_javascript tips

Using the same HTML fragment code on multiple pages_javascript tips

WBOY
WBOYOriginal
2016-05-16 18:09:581241browse

Problem Description
There is a relatively complex HTML fragment (A). If this HTML fragment is embedded into other pages (B, C, D...).
The key to the problem is that there is a lot of JavaScript logic that needs to be processed in the HTML fragment, such as paging, click event response, etc.

For this problem, we use a simple example to illustrate:
"There is a button on the page. Click this button to introduce an HTML fragment. There is a paging button in this HTML fragment."

1. Use IFrame
main page, click a button to introduce an IFrame to the page:

Copy code The code is as follows :


                                                                                                                            ="button" value="Next Page" class="next" />
                                                                                                                                                           >


2. AJAX returns page fragments and registers events
Note: We use textarea to simulate the returned HTML fragments.




Copy code


The code is as follows:

   
   
   

   

   

由于我们需要在多个页面引用同一个HTML片段,这种方法导致大量事情处理被重复性的拷贝粘贴,明显我们需要将公共的方法提取出来。

3. AJAX返回页面片段,并调用页面片段中的函数注册事件

复制代码 代码如下:

   
   
   

   

   

其实我们可以更进一步,完全没必要手工调用这个函数,而是可以在返回的HTML片段中让其自动执行。

4. AJAX返回页面片段,其事件自动注册

复制代码 代码如下: