Improvements to JS programs in Chapter 2 "click to bring up a new window" of "proficient in HTML"

Source: Internet
Author: User

In Chapter 2 "proficient in HTML: semantics, standards, and styles", there is a javascript solution for "click to bring up a new window". The Code is as follows:

function popup(){    if(!document.getElementsByTagName || !document.getElementsByTagName("a")) return false;    a = document.getElementsByTagName("a");for(i=0;i< a.length;i++) {        if(a[i].getAttribute("rel") && a[i].getAttribute("rel") == "external") {            a[i].onclick = function() {                window.open(this.getAttribute('href'));                return false;            };        }    }}

In the Web document, define the attribute REL of A as external. A new window is displayed to replace target = "_ blank ".

As the code above contains several minor bugs such as variable scope, the Code is not well written. The following is a slight improvement:

/* Popup: add all links containing external in the rel attribute in the document to bring up the function of a new window */function popup () {If (! Document. getelementsbytagname |! Document. getelementsbytagname ('A') return; VaR as = document. getelementsbytagname ('A'); var relatt; For (VAR I = 0; I <. length; I ++) {relatt = as [I]. getattribute ('rel '); If (relatt & relatt = 'external') {as [I]. onclick = function () {window. open (this. href); Return false ;}}}}

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.