What should we build a DOM

mercredi 23 janvier 2013

I have to say, the whole DOM-model we build will not, but just look at its components and how they work with jQuery. This article is intended for beginners or those who want to remember how to build elements of the "on the fly", I hope it will be useful to someone.
Most web developers faced with the need to insert any content from js, maybe it's ajax or event. But no one thinks about that with your code might require someone to work with. And often in a very well-known plug-ins you can find this type of code:

var content = "<table>" for(i=0; i<3; i++){ content += '<tr><td>' + 'result ' + i + '</td></tr>'; } content += "</table>" $('#table').append(content); 


We immediately see that this piece of code placed on a fast hand, I do so once did, but you can do better.
In this article I have drawn the most basic elements that are used in the design, maybe they will help you save time.
Under the cut with a lot of code examples.

Here's another interesting option:

 function createTable() { $("#dynamicTable").append("<table>"); $("#dynamicTable").append("<caption>My table</caption>"); $("#dynamicTable").append("<thead>"); $("#dynamicTable").append("<tr>"); $("#dynamicTable").append("<th>A</th>"); $("#dynamicTable").append("<th>B</th>"); $("#dynamicTable").append("<th>C</th>"); $("#dynamicTable").append("</tr>"); $("#dynamicTable").append("</thead>"); $("#dynamicTable").append("<tbody>"); .... } 

(So ​​just do not need it)

It's hard to tell a good code or not, but he obviously unfriendly. All elements can be created with pure Javascript, which makes itself jQuery. Why argue about the speed does not make sense, I did not measure the difference, but it is obvious that it is insignificant, we go to the code.

Div


 var mydiv = $('<div/>', { id: 'mydiv', class: 'mydiv', text: 'Содержимое блока' }); $('.content').append(mydiv); 

Example output:
 <div class="mydiv" id="mydiv">Содержимое блока</div> 
Demo

Form


 var myform = $("<form/>", { action: "/", }).appendTo('.content'); 

Example output:
 <form action="/"></form> 
Demo

Input


 $('<input/>', { id: 'myinput-1', class: 'myinput', type: 'text', name: 'myinput-1', val: 'Habr', css: { 'border': '1px solid red' } }).appendTo(myform); 

And so can:
 $('<input/>').attr({ id: 'myinput-2', class: 'myinput', type: 'text', name: 'myinput-2', placeholder: 'Поиск...' }).appendTo(myform); 


 $('<input/>', { type: 'submit', name: 'send', val: 'Отправить' }).appendTo(myform); 

Example output:
 <form action="/"> <input style="border: 1px solid red;" name="myinput-1" class="myinput" id="myinput-1" type="text"> <input placeholder="Поиск..." name="myinput-2" class="myinput" id="myinput-2" type="text"> <input value="Отправить" name="send" type="submit"> </form> 
Demo

Select


 var myselect = $('<select/>', { id: 'myselect'}); var items = ["Google","Yandex","Bing"]; //Наполняем список $.each(items,function() { $('<option/>', { val: this, text: this }).appendTo(myselect); }); myselect.val('Yandex'); $('.content').append(myselect); 

Example output:
 <select id="myselect"> <option value="Google">Google</option> <option value="Yandex">Yandex</option> <option value="Bing">Bing</option> </select> 
Demo

As you can see everything is working well, but where is our favorite selected?
Replace:
myselect.val('Yandex');
to:
$('option[value="Yandex"]', myselect).attr('selected', 'selected');
And it will work as we used to, but sometimes the first option rather

 <select id="myselect"> <option value="Google">Google</option> <option selected="selected" value="Yandex">Yandex</option> <option value="Bing">Bing</option> </select> 


Radio


 var myradiodiv = $('<div/>', { id: 'myradiodiv' }).appendTo(".content"); var items = ["Google","Yandex","Bing"]; $.each(items, function(i,item) { $('<label/>').append( $('<input/>', { type: 'radio', name: 'myradio', val: item }) ).append(item).appendTo(myradiodiv); }); 

Example output:
 <div id="myradiodiv"> <label>Google <input value="Google" name="myradio" type="radio"> </label> <label>Yandex <input value="Yandex" name="myradio" type="radio"> </label> <label>Bing <input value="Bing" name="myradio" type="radio"> </label> </div> 
Demo

Button


 var mybutton = $('<button/>', { text: 'Click Me', click: function () { alert('Hello Habr'); } }).appendTo('.content'); 

Example output:
 <button>Click Me</button> 


Iframe


 $('<iframe/>', { name: 'myframe', id: 'myframe', src: 'about:blank' }).appendTo('.content'); 

Example output:
 <iframe src="about:blank" id="myframe" name="myframe"></iframe> 


Table


<tfoot> filled similarly <thead> so I missed it

 //Данные var TableTitle = ["Site", "Google","Yandex","Bing"]; var TableValue = [ ["http://habr.ru/","4","6","26"], ["http://habrahabr.ru/","3","1","6"], ["http://google.ru/","1","1","1"] ]; //Создадим структуру var mytable = $('<table/>',{ class:'mytable' }).append( $('<thead/>'), $('<tfoot/>'), $('<tbody/>') ); //Наполняем табличку //Заголовок var TitleCell = $('<tr/>'); $.each(TableTitle,function( myIndex, myData ) { TitleCell.append( $('<th/>',{ text:myData }) ); }); $("thead",mytable).append(TitleCell); //Данные $.each(TableValue,function() { //Переопределяем строку var DataCell = $('<tr/>'); //Пробегаемся по ячейкам $.each(this,function() { DataCell.append( $('<td/>',{ text:this }) ); }); $("tbody",mytable).append(DataCell); }); //Без цикла (не обязательно) $.each(TableValue,function( i, myData ) { $("tbody",mytable).append( $('<tr/>').append( $('<td/>',{text:this[0]}), $('<td/>',{text:this[1]}), $('<td/>',{text:myData[2]}), //Или так $('<td/>',{text:myData[3]}) ) ); }); $('.content').append(mytable); 

Example output:
 <table class="mytable"> <thead> <tr> <th>Site</th> <th>Google</th> <th>Yandex</th> <th>Bing</th> </tr> </thead> <tfoot></tfoot> <tbody> <tr> <td>http://habr.ru/</td> <td>4</td><td>6</td> <td>26</td> </tr> <tr> <td>http://habrahabr.ru/</td> <td>3</td> <td>1</td> <td>6</td> </tr> <tr> <td>http://google.ru/</td> <td>1</td> <td>1</td> <td>1</td> </tr> </tbody> </table> 
Demo

Lists


 var lang = ['Russian', 'English', 'Ukraine']; var mylist = $('<ul/>'); //Наполняем $.each(lang, function() { $('<li/>',{text:this}).appendTo(mylist); //Добавим ссылку $('<li/>').wrapInner( $("<a/>",{ "href":"#", text:this })) .appendTo(mylist); }); $('.content').append(mylist); 

 <ul> <li>Russian</li> <li><a href="#">Russian</a></li> <li>English</li> <li><a href="#">English</a></li> <li>Ukraine</li> <li><a href="#">Ukraine</a></li> </ul> 
Demo

Scripts


 $("<script/>",{ src:'js/inc.js' }).appendTo("body"); 


Styles


 $("<link/>",{ href:'css/inc.css', rel:'stylesheet' }).insertAfter("link:last"); 


Construction $('<input/>') can be written and keyless $('<input>') , will work.
If anyone has comments / suggestions, I'll be glad to listen to the PM or comments.

All code on github

UPD: If you have a lot of data can be a performance problem. Let me remind you, js code is executed on the client side and the outcome depends on the configuration of the computer.
Generate a 4 column labels at 100 lines I took 36ms.
I do not want to argue about performance, which is hinted at in the beginning, if you have a solution as possible, using jQuery, to make it better, write the code.

0 commentaires:

Enregistrer un commentaire

 
© Copyright 2010-2011 GARMOBI All Rights Reserved.
Template Design by Herdiansyah Hamzah | Published by Borneo Templates | Powered by Blogger.com.