开发者

repeat code block

I have a code blocks that repeat themselvs. By writing code blocks I meen html, javascript and css that repeats in many pages. for example:

.filter {
    background-color:black;
}

$(document).ready(function(){
     $('[name=aaclick]').click(function(){ alert('aa!'); });
});

<div开发者_如何学C class="filter">
    aaa<input type="text" />
    <a name="aaclick">click</a>
</div>
  1. Can I combine those 3 parts of single unit together?
  2. How can I prevent myself from writing this code again and again in different pages?


Can I combine those 3 parts of single unit together?
You can make them closer to each other (reduce number of parts to 2, at least), but I wouldn't recommend that. Styles should stay with styles, javascript with javascript and html with html.

How can I prevent myself from writing this code again and again in different pages?
1. Put this style definition in a common css file, included in every page. Do not repeat.
2. Put this javascript code in a common js file, included in every page. Do not repeat.
3. You can reduce third part to <div class="filter"></div>, if you generate the rest of the content from javascript. Something like this

$(document).ready(function(){
    $('.filter').each(function() {
        $(this).append('aaa').append($('<input/>').attr('type', 'text'));
        ...
        $(this).find('input[name=aaclick]').click(...);
    })
});

Now, you can put only <div class="filter"></div> in html, the rest will be autogenerated.


You probably need some templating tools.


One way would be to split them into a css, js and html file, named appropriately so you know they are related.

Then use code to add them to your page, using a standard method, thus allowing you to keep the functionality together.


In case of ASP.NET simply build user control, put the whole "repeated" block as-is in the .ascx file then wherever you need it to appear have <UC:MyBlock runat="server" /> and that's it - reliable in 100%, flexible.. really no reason to mess around with client side templates, jQuery plugins and such.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜