06.05.2013 Views

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

Drupal 6 JavaScript and jQuery - Ebook-Cours.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

[ 157 ]<br />

Chapter 6<br />

For example, calling calculateSum(1, 2, 3, 4) would find the element with ID<br />

sum, <strong>and</strong> insert the HTML The sum is: 10.<br />

What we are interested in is how this function builds the information it inserts into<br />

the document.<br />

Here, the HTML <strong>and</strong> CSS are embedded in strings, which are nested inside of the<br />

programming logic. The strings are concatenated (using the + or += operators) <strong>and</strong><br />

the result is injected into the appropriate element.<br />

The method exhibited here strikes many programmers as ugly. The string<br />

concatenation code is written alongside the programming logic (the actual summing<br />

of the numbers), <strong>and</strong> the result looks jumbled.<br />

One response to this has been to get rid of the "ugly" string building code <strong>and</strong> use<br />

DOM objects. In this way, everything is essentially treated as programming logic<br />

as seen here:<br />

function calculateSum2() {<br />

var pEle = document.createElement('p');<br />

var total = 0;<br />

if (arguments.length == 0) {<br />

var pcdata = document.createTextNode(<br />

'Error: No data given.'<br />

);<br />

pEle.appendChild(txt);<br />

}<br />

else if (arguments.length == 1) {<br />

var pcdata = document.createTextNode(<br />

'Error: Cannot sum only one number'<br />

);<br />

pEle.appendChild(txt);<br />

}<br />

else {<br />

var pcdata1 = document.createTextNode('The sum is:');<br />

var spanEle = document.createElement('span');<br />

spanEle.setAttribute(<br />

'style',<br />

'color: red; font-weight: bold'<br />

);<br />

for(var i = 0; i < arguments.length; ++i) {<br />

total += arguments[i];<br />

}<br />

This material is copyright <strong>and</strong> is licensed for the sole use by Richard Ostheimer on 18th June 2009<br />

2205 hilda ave., , missoula, , 59801

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!