Ppk on JavaScript

Source: Internet
Author: User
Document directory
  • B. Hooks
  • C. Preparing the page
  • Choosing between single and double quotes
  • Last value counts
  • Return false
  • Differences between W3C and Microsoft Event-Handler Registration Models
  • Interface events: No bubbling
  • This or target?
  • HTML attributes and JavaScript Properities
  • Empty text nodes
  • Create textnode () and HTML entities

Do not under any circumstance write a script for one browser first and add support for other browers "Later on ". this is the fastest way to hell. it's far better to solve nasty incompatibilities at the start of your project than at the end.

B. Hooks

Although the class attribute might seem the ideal hook, I have two problems with it:

  • It already serves as the most important CSS hook.
  • Sometimes you need a name = value hook, and that's pretty hard to pull off in a class.

The first point is extremely subjective, the second rather less so. in the past I stronugly felt that class was a CSS hook, and that any JavaScript hook shocould use another attribute. it keeps persentation and behavior separated, and that cannot but lead
To clearer web sites where every attribute serves a clear goal.

C. Preparing the page
  • Setting event handlers

The most important action the initialization function takes is registering Event Handlers. As far as the user is concerned, the script starts when he takes action and the page responds.

The most important thing you must do in this phase is clearly picture what the user shocould to start up the script.

  • Determining visitor status
  • Setting up access
  • Generating content
  • Defining relations

Occasionally, I define relations between one HTML elements and another if an event on the first element shocould trigger changes in the other element. thus I don't have to search for the othere element when the event takes place: this bit of data has
Already been defined.

  • Modifying document structure.
Choosing between single and double quotes

Long ago I decided that I 'd always use single quotes for JavaScript and double quotes for HTML, even though both ages allow both types of marks. therefore I nearly always use single quotes to delimit JavaScript strings.

I advise you to make such a rule for yourself, since it'll make your code more readable and will occasionally prevent errors.

Last value counts

It is important to realize that the nested function has access only to the final value of a local variable. the next example, which looks a bit like the previous one, doesn' t do what you might wrong CT:

function init(){    var message = ' Clicked - ';    var x = document.getElementsByTagName('a');    for(var i=0; i<x.length; i++){         x[i].onClick = function(){              x[i].firstChild.nodeValue = message;       }    }}

Here, too, an event handler is defined within another function, and therefore has access to the local variables of that function. In the Case ofi, though, it doesn't work as expected.

The function Init () defines Event Handlers on all
<A> tags in the Document. Let's say we have 10. During that process, I goes from 0 to 10, and when the function exits, it retains this final value 10.

The Event Handlers fire long after the function has exited, and by that time I has the value 10. therefore, the event handler uses this value, and that causes an error. since the tenth link in the document has Index Number 9, the event handler gives an error
Message: It can't find the eleventh Link (with index 10) in the document.

The solution is to use the this keyword instead:

x[i].onclick = function(){    this.firstChild.nodeValue = message;}
Return false

Event Handlers can become methods of the object you register them on provided you register them correctly. Return false works only from a function that is directly assigned as a method of an HTML element.

Return false works in this case:

var x = document.getElementsByTagName('a');for(var i=0; i<x.length; i++){    x[i].onclick = askConfirmation;}

This, however, does not work:

var x = document.getElementsByTagName('a');for(var i=0; i<x.length; i++) {    x[i].onclick = function(){        askConfirmation();       }}

Now the onclick method of The Link CILS askconfirmation (), and although the function still returns true or false, this return value is not caught, and disappears without a trace.

A return false in an event handler works in the following cases:

x.onclick = askConfirmation;x.addEventListener('click', askConfirmation, false);x.attachEvent('onclick', askConfirmation);

It does not work in the following cases:

<element onclick="askConfirmation()">x.onclick = function(){    askConfirmation();}x.addEventListener('click', function(){    askConfirmation();},false);

An extra Return Statement will suffice to get these last examples in line:

<element onclick="return askConfirmation()">x.onclick = function(){    return askConfirmation();}x.addEventListener('click', function(){    return askConfirmation();},false);

Differences between W3C and Microsoft Event-Handler Registration Models

W3C model:

x.addEventListener('click', doThis, false);

Microsoft model:

x.attachEvent('onclick',doThis);

  • The Microsoft model does not support event capturing. Since you rarely use capturing anyway, this is not a big problem
  • The Microsoft model treats the event-handling function as a global function, not a method of the HTML element it's registered on. that means that thethis keyword refers to the window instead of the object the event
    Handler is registered on.
Interface events: No bubbling

You cannot use event bubbling in all situations, because some events are not valid on some HTML elements. the most restrictive rule is that interface events such as change or submit don't work on the document or window.

As a general rule, you can catch mouse and keyboard events on the document level, but not interface events. however, you shoshould always test this general rule for your specific events and browsers you might get lucky.

This or target?

When do you use the this keyword and when do you use the event Target? There are a few general rules, but there's also a lot of overlap, especially when you have registered the event on the same element that will be the event target.

  • In general, the this keywords is useful when you register the event handler on a lot of elements and/or when you want to call the Event Handlers directly, I. E ., without an event taking place.
  • In general, the event target is useful when you rely on Bubbling to take the event upward in the document tree.
HTML attributes and JavaScript Properities

if(containers[i].getAttribute('price'))    currentPrice = containers[i].getAttribute('price');containers[i].price = currentPrice;

The first two lines read the HTML custom attribute price and then set currentprice to its value. The third line sets the Javascript price property of the <tr> to the value of currentprice.

Even though they share a name, the HTML custom attribute price and the JavaScript property are different things. the HTML attribute is located in the document tree as an attribute node of the <tr>, while the JavaScript property belongs to the object that
Represents the <tr> and is not present in the document tree.

Empty text nodes

Normal text nodes are easy to work. unfortunately, there are also empty text nodes. they are by far the most useless and annoying feature of the W3C Dom, but you'll encounter them in every HTML document you work.

Consider this HTML snippet:

<body>

How many child nodes does the <body> have? Two, right? The

Wrong.

The <body> has five child nodes. two of them are element nodes, the other three are empty text nodes. there is text between the tags: A Hard Return between the <body> and the Between the </Body>. Since spaces, hard returns, and tabs are text content, the W3C Dom creates text nodes to hold them. (Explorer Windows does not support empty text nodes .)

Their first victims are the previussibling and nextsibling properties, which are rather useless since they usually refer to empty text nodes. The same happens to childnodes [].

The only situation in which properties like nextsibling are useful is when you construct a document tree, or a portion of one, entirely in JavaScript. then it contains no empty text nodes, and all properties work as you have CT them to work.

Create textnode () and HTML entities

There's one problem with createtextnode (): it cannot Create HTML entities like & copy; or & #8212;. Instead of the symbol you need, it creates the literal text:

var x = document.createTextNode(' Copyright reserved');document.getElementById('test').appendChild(x);

Use innerhtml instead:

document.getElementById('test').innerHTML = ' Copyrights reserved';

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.