Your SlideShare is downloading. ×
Scti 2011 minicurso jquery
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Scti 2011 minicurso jquery

953
views

Published on

Slides do minicurso "Javascript + JQuery: With great power, comes great responsability" apresentado no SCTI 2011 (http://scti.uenf.br/2011).

Slides do minicurso "Javascript + JQuery: With great power, comes great responsability" apresentado no SCTI 2011 (http://scti.uenf.br/2011).

Published in: Technology, Design

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
953
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
22
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Javascript + jQuery: With great power, comes great responsibility http://www.slideshare.net/ciberglo/scti-2011-minicurso-jquery Gabriel Lima @glima5 github.com/gabriellima
  • 2.  
  • 3.  
  • 4.  
  • 5. Balanceando: Básicos
    • typeof("") == "string"
    • 6. typeof(0) == "number"
      • "2" + "2" = "22"
    • typeof(true) == "boolean"
    • 7. if ( 4 && !0 && "test" && !"" && !undefined && { } ){
    • 8. alert("true");
    • 9. }
  • 10. Balanceando: Funções
  • 11. Balanceando: Objetos
    • Tudo que não é uma string, um número ou booleano
    • 12. var shape = new Shape();
    • 13. var obj = { }; // Object literal, == "new Object()"
    • 14. var arr = [ ]; // Array literal, == "new Array()"
    • 15. var exp = /[0-9a-z]/ig; // reg exp literal
  • 16. Balanceando: Hashes
    • Objetos podem ser manipulados como hashes:
    • 17. var lastNames = { };
    • 18. lastNames["Jason"] = "Horton";
    • 19. lastNames["Matheu"] = "Chambers";
    • 20. lastNames["Rohit"] = "Mistry";
    • 21. for ( var key in lastNames ) {
    • 22. alert( key + " " + lastNames[key] );
    • 23. }
  • 24. Exemplo: Array sorting
      var arr = ["a","f","Z","b","x", "o", "A"].sort(); // retorna ["A", "Z", "a", "b", "f", "o", "x"] ... rápido mas não tão legal...
  • 25. Exemplo: Array sorting
    • var arr = ["a","f","Z","b","x", "o", "A"].sort( by_alpha )
    • 26. // retorna ["a", "A", "b", "f", "o", "x", "Z"] ... mais útil
  • 27. Scope var iAmGlobal = 5 * 5; function doSomething() { var inner = 5 * 5; }; var g = "global"; function go() { var l = "local"; } go(); console.log(l); // throws a reference error
  • 28. Scope: How it works function go() { console.debug(this); } go(); var myObject = { go: function() { console.debug(this); } }; myObject.go(); // console.debugs a reference to myObject
  • 29. Scope: How it works function MyClass() { this.go = function() { console.debug(this); } }; var instance1 = new MyClass(); var instance2 = new MyClass(); instance1.go(); // console.debugs a reference to the MyClass instance1 instance2.go(); // console.debugs a reference to the MyClass instance2
  • 30. Qual o lugar do javascript?
    • JavaScript é bom para cálculo, conversão, acesso a fontes externas (Ajax) e definição de comportamentos na interface (eventos).
    • 31. Todo o resto deve ser deixado pra tecnologia que temos pra fazer o serviço.
  • 32.  
  • 33. Progressive enhancement
    • Web Page :: Printed page
    • 34. Web Site – Web Browser ?
    • 35. Não!
    • 36. Web Browser – Web Page
    • 37. Televisão – Show de música
    • 38. Sim!
  • 39.  
  • 40. Progressive enhancement 2.0
  • 41. Progressive enhancement 2.0
    • Chrome
  • 42. Progressive enhancement 2.0
    • Firefox
  • 43. Progressive enhancement 2.0
    • IE 9
  • 44. Progressive enhancement 2.0
    • IE 6
  • 45. Progressive enhancement 2.0
    • Netscape 4
  • 46. Melhor experiência de acordo com capacidade do dispositivo
  • 47.
    • Bordas curvas, Sombra, Gradient -> CSS
    • 48. Script avançado e comportamentos -> somente com APIs javascript nativas
    • 49. Navegadores antigos quase sempre precisam de muito mais código pra fazer a mesma coisa!
  • 50.  
  • 51.  
  • 52.
    • Mas as pessoas não vão notar?
  • 53.  
  • 54.
      O que você viu?
  • 55.  
  • 56.  
  • 57. Você não está sozinho
  • 58. Keep javascript out of HTML
    • <button onclick='do_something()'>wrong!</a>
    • 59. <button id='do_search'>better!</button>
    • 60. (function(){ var search_button = document.getElementById('do_search'); search_button.onclick = function(event) { do_something(); } })();
  • 61. HTML vs Javascript
    • Fuja de inserir HTML diretamente no código javascript
    • 62. Se você percebe que está digitando muito código HTML num codigo javascript, você deve estar fazendo algo errado
  • 63. Keep HTML out of Javascript
      var element = document.getElementById('container'); element.innerHTML = “<div class=”popup”></div>”
  • 64. Keep Javascript out of CSS
      .foo { width: expression(document.offsetwidth + “px”); }
  • 65. Keep CSS out of Javascript
    • Estilos não devem ser confundidos com comportamentos
    • 66. Exemplo: borda vermelha
      • Coloque uma borda vermelha em todos campos com uma classe “required” quando estiverem vazios.
  • 67. Exemplo: borda vermelha
  • 68. Exemplo: borda vermelha
  • 69. Event handlers should only handle events //the wrong way!!! function handleClick(event){ var popup = document.getElementById(&quot;popup&quot;); popup.style.left = event.clientX + &quot;px&quot;; popup.style.top = event.clientY + &quot;px&quot;; popup.className = &quot;reveal&quot;; }
  • 70. Don't pass the event object around //better, but still wrong function handleClick(event){ showPopup(event); } function showPopup(event){ var popup = document.getElementById(&quot;popup&quot;); popup.style.left = event.clientX + &quot;px&quot;; popup.style.top = event.clientY + &quot;px&quot;; popup.className = &quot;reveal&quot;; }
  • 71. Separe corretamente os event handlings //fuck yeah!! function handleClick(event){ showPopup(event.clientX, event.clientY); } function showPopup(x, y){ var popup = document.getElementById(&quot;popup&quot;); popup.style.left = x + &quot;px&quot;; popup.style.top = y + &quot;px&quot;; popup.className = &quot;reveal&quot;; }
  • 72. Avoid global functions and variables function handleClick(event){ showPopup(event.clientX, event.clientY); } function showPopup(x, y){ var popup = document.getElementById(&quot;popup&quot;); popup.style.left = x + &quot;px&quot;; popup.style.top = y + &quot;px&quot;; popup.className = &quot;reveal&quot;; }
  • 73. Create a single global (se necessário) var Controller = { handleClick: function(event){ this.showPopup(event.clientX, event.clientY); }, showPopup: function (x, y){ var popup = document.getElementById(&quot;popup&quot;); popup.style.left = x + &quot;px&quot;; popup.style.top = y + &quot;px&quot;; popup.className = &quot;reveal&quot;; } };
  • 74. Separe configurações function validate(value) { if (!value) { alert(&quot;Invalid value&quot;); location.href = &quot;/errors/invalid.php&quot;; } };
  • 75. Separe configurações var config = { urls: { invalid: &quot;/errors/invalid.php&quot; }, strs: { invalidmsg: &quot;Invalid value&quot; } }; function validate(value) { if (!value) { alert(config.strs.invalidmsg); location.href = config.urls.invalid; } };
  • 76. Separe configurações
    • Todas URLs requeridas pelo javascript
    • 77. Qualquer texto exibido para o usuário
    • 78. Qualquer HTML que precisa ser criado pelo javascript
    • 79. Configurações (exemplo: itens por página)
    • 80. Valores únicos repetidos
    • 81. Qualquer coisa que talvez seja modificada no futuro, e utilizada em mais de um lugar
  • 82. Otimizando Loops: var names = ['George','Ringo','Paul','John']; for(var i=0;i<names.length;i++){ doSomeThingWith(names[i]); } var names = ['George','Ringo','Paul','John']; var all = names.length; for(var i=0;i<all;i++){ doSomeThingWith(names[i]); }
  • 83. var names = ['George','Ringo','Paul','John']; for(var i=0,j=names.length;i<j;i++){ doSomeThingWith(names[i]); }
    • Mantenha processamento pesado fora de loops
    • 84. Isso inclui expressões regulares, mas primeiro e mais importante: DOM manipulation (CAUTION!)
    • 85. Você pode criar nós do DOM no loop, mas evitar sua inserção no documento
  • 86. Repaint vs Reflow
  • 87. Repaint
    • ...is what happenswhenever something is made visible when it was not previously visible, or vice versa, without altering the layout of the document.
    • 88. - Mark 'Tarquin' Wilton-Jones, Opera
  • 89. When Repaint?
    • Change to 'visibility'
    • 90. Formatting style changes
      • Backgrounds
      • 91. Borders
      • 92. Colors
      • 93. Anything that doesn't change the size, shape or position of element but change appearance
    • When a reflow occurs
  • 94. Reflow
    • ...is the process by which the geometry of the layout engine's formatting objects are computed.
    • 95. - Chris Waterson, Mozilla
  • 96. When Reflow?
    • Initial page load
    • 97. Browser window resize
    • 98. DOM nodes added or removed
    • 99. Layout styles applied
    • 100. Layout information retrieved
  • 101. O que fazer?
    • Fazer modificações no DOM “off-document”
    • 102. Agrupar modificações de estilos
    • 103. Cachear informações de layout
  • 104.  
  • 105. Off-Document operations
    • Rápido porque não há repaint/reflow
    • 106. Técnica:
      • Easy: Remover elemento do documento, aplicar modificações, inserir o elemento de volta
      • 107. Medium: Colocar 'display' do elemento como 'none', aplicar modificações, colocar 'display' volta ao padrão
      • 108. Fuck yeah!: Construir modificações do DOM num 'DocumentFragment' e depois aplicar tudo de uma vez
  • 109. DocumentFragment
    • Quase um 'document'
    • 110. Não tem representação visual
    • 111. Seu pai é o document que o gerou
    • 112. Quando passado para 'appendChild()', adiciona todos seus filhos ao invés de si próprio
  • 113.  
  • 114.
    • Fazer modificações no DOM “off-document”
    • 115. Agrupar modificações de estilos
    • 116. Cachear informações de layout
  • 117.  
  • 118. O que fazer?
    • Minimizar modificações na propriedade 'style'
    • 119. Definir a classe CSS com todas modificações e então apenas modificar a propriedade 'className'
    • 120. Definir diretamente o 'cssText' no elemento
  • 121.  
  • 122.  
  • 123.
    • Fazer modificações no DOM “off-document”
    • 124. Agrupar modificações de estilos
    • 125. Cachear informações de layout
      • Reflow talvez seja cacheado
  • 126.  
  • 127. O que fazer?
    • Minizar acesso as informações de layout
    • 128. Se um valor é usado mais de uma vez, armazene-o em uma variável local
  • 129. Responsive UI Interface
    • UI Thread: high-performance-javascript-2011-110918100745-phpapp02.pptx
  • 130.
      <button id=&quot;btn&quot; style=&quot;font-size: 30px; padding: 0.5em 1em&quot;>Click Me</button> <script type=&quot;text/javascript&quot;> window.onload = function (){ document.getElementById(&quot;btn&quot;).onclick = function (){ //do something }; }; </script>
  • 131.
      Quando clicado
    • A button UI change job is created
      • Draws the button in the down state
    • A JavaScript execution job is created
      • The onclick event handler
    • A button UI change job is created
      • Draws the button in the up state
  • 132.
      Before Click
      Start
      UI Thread
      UI Queue
  • 133.
      When Clicked
      Start
      UI Thread
      onclick
      UI Queue
  • 134.
      When Clicked
      Start
      UI Thread
      onclick
      UI Queue
  • 135.
      When Clicked
      onclick
      Start
      UI Thread
      UI Queue
  • 136.
      When Clicked
      onclick
      Start
      UI Thread
      UI Queue
  • 137.
      Não há UI updates enquanto JavaScript está executando!
  • 138.
      Por quê?
  • 139.
      JavaScript May Cause UI Update
      <button id=&quot;btn&quot; style=&quot;font-size: 30px; padding: 0.5em 1em&quot;>Click Me</button> <script type=&quot;text/javascript&quot;> window.onload = function (){ document.getElementById(&quot;btn&quot;).onclick = function (){
      var div = document.createElement(“div”); div.className = “tip”; div.innerHTML = “You clicked me!”; document.body.appendChild(div);
      }; }; </script>
  • 140.
      UI updates devem usar a última informação disponível
  • 141.
      Long-running JavaScript = Unresponsive UI
  • 142.
      Runaway Script Timer
    • Projetada para previnir que o browser afete o OS
    • 143. Limita a qtd. de tempo que um script tem para ser executado
    • 144. 2 tipos delimites:
      • Tempo de execução
      • 145. Número de statements (stack)
    • Sempre gera um pop up horroroso pro usuário
    • 146. Exceção: Opera não tem runaway timer
  • 147.
      Internet Explorer
  • 148.
      Firefox
  • 149.
      Safari
  • 150.
      Chrome
  • 151.
      Runaway Script Timer Limits
    • Internet Explorer: 5 million statements
    • 152. Firefox: 10 seconds
    • 153. Safari: 5 seconds
    • 154. Chrome: Unknown, hooks into normal crash control mechanism
    • 155. Opera: none
  • 156.
      How long is too long?
  • 157.
      How Long Is Too Long?
      “ 0.1 second [100ms] is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.” - Jakob Nielsen
  • 158.
      Translation: JavaScript não deve ser executado por mais do que 100ms para garantir uma responsive UI
  • 159.
      Recommendation: Limitar o JavaScript para não mais do que 50ms at a time
  • 160.
      function processArray(items, process, callback){
      for ( var i=0,len=items.length; i < len; i++){ process(items[i]); } callback(); }
  • 161.
      Timers to the rescue!
  • 162.
      JavaScript Timers
    • Created using setTimeout()
    • 163. Schedules a new JavaScript execution job for some time in the future
    • 164. When the delay is up, the job is added to the UI queue
      • Note: This does not guarantee execution after the delay, just that the job is added to the UI queue and will be executed when appropriate
  • 165.
      JavaScript Timers
    • For complex processing, split up into timed functionality
    • 166. Use timers to delay some processing for later
  • 167.
      function timedProcessArray(items, process, callback){
      //create a clone of the original var todo = items.concat(); setTimeout(function(){ var start = +new Date(); do { process(todo.shift()); } while (todo.length > 0 && (+ new Date() - start < 50)); if (todo.length > 0){ setTimeout(arguments.callee, 25); } else { callback(items); } }, 25); }
  • 168.
      Web Workers to the rescue!
  • 169.  
  • 170.
      Web Workers
    • Asynchronous JavaScript execution
    • 171. Execution happens in a separate process
      • Not on the UI thread = no UI delays
    • Data-driven API
      • Data is serialized when sending data into or out of Worker
      • 172. No access to DOM, BOM
      • 173. Completely separate execution environment
  • 174.
      //in page var worker = new Worker(&quot;code.js&quot;);
      worker.onmessage = function (event){ alert(event.data); }; worker.postMessage(&quot;Nicholas&quot;);
      //in code.js
      self.onmessage = function (event){ self.postMessage(&quot;Hello, &quot; + event.data + &quot;!&quot;); };
  • 175.
      Resumo de Responsive UI
    • UI thread is used both for JavaScript execution and UI updates
    • 176. UI cannot be updated while JavaScript is executing
    • 177. Keep JavaScript execution to 50ms – use timers and/or web workers to offload processing
  • 178. Jquery: Traversing
  • 179. jQuery
    • Um “Faz quase tudo” da vida
    • 180. Porém, deve ser usado com cautela, pois ao mesmo tempo que pode melhorar o código pode às vezes prejudicar a performance
    • 181. Principal teoria: html / css selectors
    • 182. http://code.jquery.com/jquery-latest.js
    • 183. // jQuery 1.7
  • 184. Jquery: Traversing
    • O HTML
      • div.container é o 'wrapping element'
      • 185. div.photo, div.title and div.rating são filhos 'imediatos' do div.container
      • 186. Cada div.star é filho de div.rating
      • 187. Quando uma div.star tem a class 'on', é uma estrela selecionada
  • 188. Mas por quê traversing?
    • “O select do jQuery já não é poderoso o suficiente?”
  • 189. Jquery: Traversing
    • Bem, no exemplo anterior, queremos que quando o usuário clicar numa dada estrela, todas as estrelas à esquerda sejam também selecionadas, e todas as direita não sejam selecionadas
    $('.star').click(function(){ $(this).addClass('on'); // How to select the parent div of 'this'? // How to select stars to the left side of 'this'? });
  • 190. .children
    • This function gets the immediate children of a set of elements.
    • 191. This can be very handy in a variety of situations. Look at the figure below:
      • The container of the stars are selected initially.
      • 192. A selector expression is passed to children() to narrow the result down to only the full stars.
      • 193. If children() receives no parameters, all immediate children will be returned.
      • 194. No grandchildren will be returned. Sorry.
  • 195. .children
  • 196. .filter
    • This function filters out elements from the wrapped set using a passed selector expression. Any elements that doesn’t match the expression will be removed from the selection.
    • 197. The following example should be pretty straightforward. The full stars are filtered out from a collection of all five stars.
  • 198. .not
    • Quite the opposite from filter(), not() removes the matching elements from the wrapped set.
    • 199. See the example below. Even stars are removed from the selection, leaving only the odd ones.
    • Notice! “Even” and “odd” selectors are zero-indexed. They count index from 0, NOT 1.
  • 200. .add
    • What if we want to add some elements to the wrapped set? The add() function does this.
    • 201. Again, very straightforward. The photo box is added to the selection.
  • 202. .slice
    • Sometimes we may wish to obtain a subset of the wrapped set, based on the position of elements within the set. And slice() is the way to go.
      • The first parameter is the zero-based position of the first element to be included in the returned slice.
      • 203. The second parameter is the zero-based index of the first element NOT to be included in the returned slice. If omitted, the slice extends to the end of the set.
      • 204. So slice(0, 2) selects the first two stars.
  • 205. .slice
  • 206. .parent
    • The parent() function selects the direct parent of a set of elements.
    • 207. As shown in the figure below, the first star’s direct parent is selected. Very handy, hah?
    • 208. It should be noted that only the direct parent will be returned, which is why it’s singular. No grandparent or ancestors will be selected.
  • 209. .parents
    • This one is plural! The parents() function selects all ancestors of a set of elements. I mean ALL ancestors from the direct parent all the way up to ‘body‘ and ‘html‘. So it’s best to pass a selector expression to narrow down the result.
    • 210. By passing ‘.container‘ to parents(), div.container, which actually is the grandparent of the first star, is selected.
  • 211. .siblings
    • This function selects all siblings (brothers and sisters) of a set of elements. An expression can be passed to filter the result.
    • 212. Look at the example:
      • Who’s the first star’s siblings? The other four stars, right?
      • 213. The ‘odd’ siblings are selected as shown. Again, the index is zero-based. Look at the red numbers below the stars.
  • 214. .prev e .prevAll
    • The prev() function selects the previous (one) sibling
    • 215. The prevAll() selects all previous siblings of a set of elements.
    • 216. This is super handy if you’re building a star rating widget. The previous siblings of the third star are selected.
  • 217. .next e .nextAll
    • These functions work in the same way as prev and prevAll, except for that they select the NEXT siblings.
  • 218. Traversing - Solução
    • Vejamos como essa função resolve nossa dor de cabeça:
    $('.star').click(function(){ $(this).addClass('on'); // How to select the parent div of 'this'? $(this).parent().addClass('rated'); // How to select stars to the left side of 'this'? $(this).prevAll().addClass('on'); $(this).nextAll().removeClass('on'); });
  • 219. Traversing
    • This is the very problem we mentioned early in this tutorial, right? Several traversing functions are used in these lines of code.
      • In Line 5, look at the use of parent(). Easy, hah?
      • 220. In Line 8 and 9, prevAll() and nextAll() select the to-be full stars and empty stars.
    • Traversing can be even more powerful when used together.
    • 221. The output of one function can be the input of another – that is to say, they’re chainable .
  • 222. Multi-select transfer $().ready(function() { $('#add').click(function() { return !$('#select1 option:selected').appendTo('#select2'); }); $('#remove').click(function() { return !$('#select2 option:selected').appendTo('#select1'); }); });
  • 223. Multi-transfer <html> <head> <script src=&quot;jquery-latest.js&quot; type=&quot;text/javascript&quot;></script> <script type=&quot;text/javascript&quot;> $().ready(function() { $('#add').click(function() { return !$('#select1 option:selected').remove().appendTo('#select2'); }); $('#remove').click(function() { return !$('#select2 option:selected').remove().appendTo('#select1'); }); }); </script> <style type=&quot;text/css&quot;> a { display: block; border: 1px solid #aaa; text-decoration: none; background-color: #fafafa; color: #123456; margin: 2px; clear:both; } div { float:left; text-align: center; margin: 10px; } select { width: 100px; height: 80px; } </style> </head> <body> <div> <select multiple id=&quot;select1&quot;> <option value=&quot;1&quot;>Option 1</option> <option value=&quot;2&quot;>Option 2</option> <option value=&quot;3&quot;>Option 3</option> <option value=&quot;4&quot;>Option 4</option> </select> <a href=&quot;#&quot; id=&quot;add&quot;>add &gt;&gt;</a> </div> <div> <select multiple id=&quot;select2&quot;></select> <a href=&quot;#&quot; id=&quot;remove&quot;>&lt;&lt; remove</a> </div> </body> </html>
  • 224. Select all $('form').submit(function() { $('#select2 option').each(function(i) { $(this).attr(&quot;selected&quot;, &quot;selected&quot;); }); });
  • 225. .append
    • Talvez o método mais erroneamente utilizado no jQuery
    • 226. Extremamente útil, se souber utilizá-lo devidamente
    • 227. Exemplo de código ruim:
  • 228. .append
  • 229. .append
  • 230. .append
  • 231. .append
  • 232. .append
    • .each com callback function será sempre mais lento que iterar diretamente sobre o array em javascript
    • 233. A última solução poderia ser ainda melhorada, salvando antecipadamente o atributo '.length'
  • 234. .append var arr = [1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf', 1, 2, 3, 4, 5, 'adsf', 'as', 6, 2, 3, 6, 'ffadscdasc', 'cada', '2wd', 3, 7, 3, 2, 'sdf'];
  • 235. Events
    • .bind() and .unbind()
    • 236. .click()
    • 237. .live() and .die()
  • 238. Event .toggle and animation .toggle <html> <head> <style> ul { margin:10px; list-style:inside circle; font-weight:bold; } li { cursor:pointer; } </style> <script src=&quot;jquery-latest.js&quot;></script> </head> <body> <ul> <li>Go to the store</li> <li>Pick up dinner</li> <li>Debug crash</li> <li>Take a jog</li> </ul> <script> $(&quot;li&quot;).toggle( function () { $(this).css({&quot;list-style-type&quot;:&quot;disc&quot;, &quot;color&quot;:&quot;blue&quot;}); }, function () { $(this).css({&quot;list-style-type&quot;:&quot;disc&quot;, &quot;color&quot;:&quot;red&quot;}); }, function () { $(this).css({&quot;list-style-type&quot;:&quot;&quot;, &quot;color&quot;:&quot;&quot;}); } ); </script> </body> </html>
  • 239. Chrome permissions chromium-browser --allow-file-access-from-files
  • 240. Jquery AJAX
    • jQuery.get( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
    $.ajax({ url: url, data: data, success: success, dataType: dataType });
    • jQuery.ajax( url [, settings] )
    • 241. .load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
  • 242. .get or .load? $.get('ajax/test.html', function(data) { $('.result').html(data); alert('Load was performed.'); }); $('.result').load('ajax/test.html', function(){ console.log('finished!'); }); $('#b').load('article.html #target');
  • 243. .load $(&quot;#success&quot;).load(&quot;/not-here.php&quot;, function(response, status, xhr) { if (status == &quot;error&quot;) { var msg = &quot;Sorry but there was an error: &quot;; $(&quot;#error&quot;).html(msg + xhr.status + &quot; &quot; + xhr.statusText); } });
  • 244. Referências
    • Em construção...

×