JavaScript Tabs con Javascript

http://www.barelyfitz.com/projects/tabber/

JavaScript 创建Cookie

see: http://www.howtocreate.co.uk/tutorials/javascript/cookies

JavaScript 创建对象

// --------------------------------------------------
//    Creating an object with methods

function mycircle(x,y,r) {
  this.xcoord = x;
  this.ycoord = y;
  this.radius = r;
  this.retArea = getTheArea;
  //This next line uses an alternative syntax
  this.retCirc = function () { return ( Math.PI * this.radius * 2 ); };
  this.mvBy = mvCclBy;
}
function getTheArea() {
  return ( Math.PI * this.radius * this.radius );
}
function mvCclBy(xDis,yDis) {
  this.xcoord += xDis;
  this.ycoord += yDis;
}

/*
create a mycircle called testcircle where testcircle.xcoord is 3
and testcircle.ycoord is 4 and testcircle.radius is 5
*/
var testcircle = new mycircle(3,4,5);
/*
use the mvBy method to displace the centre of testcircle.
move it by 2 in the x direction and 3 in the y direction
*/
testcircle.mvBy(2,3);
//testcircle.xcoord is now 5 and testcircle.ycoord is now 7

window.alert( 'The area of the circle is ' + testcircle.retArea() );
window.alert( 'The circumference is ' + testcircle.retCirc() );


// --------------------------------------------------
//    Advanced object techniques

testcircle.texture = 'smooth';
mycircle.prototype.texture = 'smooth';  
// all of the mycircles that we have created will now inherit the new property:

alert(testcircle.texture);
//alerts 'smooth'

mycircle.prototype.setArea = function (oArea) {
  this.radius = Math.sqrt( oArea / Math.PI );
};
mycircle.setArea(5);


function mycircle(x,y,r) {
  this.xcoord = x;
  this.ycoord = y;
  this.radius = r;
}
mycircle.prototype.retArea = function () {
  return ( Math.PI * this.radius * this.radius );
};
mycircle.prototype.retCirc = function () {
  return ( Math.PI * this.radius * 2 );
};
mycircle.prototype.mvBy = function (xDis,yDis) {
  this.xcoord += xDis;
  this.ycoord += yDis;
};


// --------------------------------------------------
//    Sub-classes and class inheritance

/*
This effectively makes mysphere a sub-class of mycircle, and making the mysphere class constructor inherit from the mycircle class constructor is as simple as this:
*/
function mysphere(x,y,z,r) { ... constructor code ... }
mysphere.prototype = new mycircle();

------------

function mycircle(x,y,r) {
  if( arguments.length ) { this.getready(x,y,r); }
}
mycircle.prototype.getready = function (a,b,c) {
  this.xcoord = a;
  this.ycoord = b;
  this.radius = c;
};
mycircle.prototype.retArea = function () {
  return ( Math.PI * this.radius * this.radius );
};
mycircle.prototype.retCirc = function () {
  return ( Math.PI * this.radius * 2 );
};
mycircle.prototype.mvBy = function (xDis,yDis) {
  this.xcoord += xDis; this.ycoord += yDis;
};

-------

function mysphere(x,y,z,r) {
  if( arguments.length ) { this.getready(x,y,z,r); }
}
//inherit from the mycircle prototype
mysphere.prototype = new mycircle();
//put the correct constructor reference back (not essential)
mysphere.prototype.constructor = mysphere;

mysphere.prototype.getready = function (a,b,c,d) {
  //reference the getready method from the parent class
  this.tempReady = mycircle.prototype.getready;
  //and run it as if it were part of this object
  this.tempReady(a,b,d);
  //now that all required properties have been inherited
  //from the parent class, define extra ones from this class
  this.zcoord = c;
}
mysphere.prototype.mvBy = function (xDis,yDis,zDis) {
  //override the existing method
  this.xcoord += xDis;
  this.ycoord += yDis;
  this.zcoord += zDis;
};
mysphere.prototype.retVol = function () {
  return ( 4 / 3 ) * Math.PI * Math.pow( this.radius, 3 );
};
mysphere.prototype.retSurf = function () {
  return 4 * Math.PI * this.radius * this.radius;
};

--------

//  to use it
var testsphere = new mysphere(3,4,5,6);

alert( 'The cross-section area is ' + testsphere.retArea() );
alert( 'The circumference is ' + testsphere.retCirc() );
alert( 'The volume is ' + testsphere.retVol() );
alert( 'The surface area is ' + testsphere.retSurf() );

JavaScript javascript MVC

<html>
<head>
<script type=”text/javascript” xsrc=”js-mvc.js” mce_src=”js-mvc.js” /> </head>
<body onload=”init()”>
<form>
<input type=”button” id=”myBtn” name=”myBtn”/>
<p id=”label”>0 clicks</p>      </form>
</body>
</html>

var myBtn = null;var label = null;

function init()

{

myBtn = document.getElementById(”myBtn”);

label = document.getElementById(”label”);

myBtn.onclick = myBtnOnClick;

}

function myBtnOnClick()

{

var labelContents = parseInt(label.innerHTML);

labelContents++;

label.innerHTML = labelContents + ” clicks”;

}

JavaScript 活动信息

/*
Input, textarea, select
-> onclick, onkeydown, onkeyup, onkeypress, onchange, onfocus, onblur, etc.
form
-> onsubmit, onreset
a
-> onclick, onmouseover, onmouseout, onfocus, onblur
body
-> onload, onunload
*/ 

// ------------------------------
//     reacting to an event

<a onmouseover="name_of_function(params)" href="somepage.html">
<input onkeypress="myVariable = 2;startTest();">
<select onchange="self.location.href = this.options[this.selectedIndex].value;">
<body onunload="window.alert('bye')">

// ------------------------------
//     Executing a function

<a href="javascript:name_of_function(params)">


// ------------------------------
//     Accommodating Netscape 4

//Only Netscape 4 and Escape 4 need this first line
if( document.captureEvents && Event.KEYUP ) { document.captureEvents( Event.KEYUP ); }
document.onkeyup = alertkey;
//where alertKey is a function that will handle the event


// ------------------------------
//     Detecting the keyup event over the page and extracting 
//     the key code.

/*
-> iCab only passes key code information in input boxes.
-> Blazer (a version of NetFront) detects limited key events (due to the keyboard handling on the device) and returns nonsense key codes (such as -1987304).
-> WebTV and Escape 4 can only detect key events on text boxes, and may be a little unreliable.
-> OmniWeb 4.2- and Opera 5 for Mac do not pass key code information.
-> Netscape 4 on Linux does not detect any key events properly.
-> Clue browser cannot detect key events.
I am unsure of the capabilities of NetBox, iPanel MicroBrowser and OpenTV here.

*/

// first, tell the browsers to react to the event
if( document.captureEvents && Event.KEYUP ) {
  //remove this part if you do not need Netscape 4 to work
  document.captureEvents( Event.KEYUP );
}
/* this next line tells the browser to detect a keyup
event over the whole document and when it detects it,
it should run the event handler function 'alertkey' */
document.onkeyup = alertkey;

//now create the event handler function to process the event
function alertkey(e) {
  if( !e ) {
    //if the browser did not pass the event information to the
    //function, we will have to obtain it from the event register
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  if( typeof( e.keyCode ) == 'number'  ) {
    //DOM
    e = e.keyCode;
  } else if( typeof( e.which ) == 'number' ) {
    //NS 4 compatible
    e = e.which;
  } else if( typeof( e.charCode ) == 'number'  ) {
    //also NS 6+, Mozilla 0.9+
    e = e.charCode;
  } else {
    //total failure, we have no way of obtaining the key code
    return;
  }
  window.alert('The key pressed has keycode ' + e +
    ' and is key ' + String.fromCharCode( e ) );
}



// ------------------------------
//     Detecting the mouse coordinates when it moves 
//     over a positioned element </h3>

if( myReference.captureEvents && Event.MOUSEMOVE ) {
  //remove this part if you do not need Netscape 4 to work
  myReference.captureEvents( Event.MOUSEMOVE );
}
myReference.onmousemove = alertCoord;

function alertCoord(e) {
  if( !e ) {
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  if( typeof( e.pageX ) == 'number' ) {
    //most browsers
    var xcoord = e.pageX;
    var ycoord = e.pageY;
  } else if( typeof( e.clientX ) == 'number' ) {
    //Internet Explorer and older browsers
    //other browsers provide this, but follow the pageX/Y branch
    var xcoord = e.clientX;
    var ycoord = e.clientY;
    var badOldBrowser = ( window.navigator.userAgent.indexOf( 'Opera' ) + 1 ) ||
     ( window.ScriptEngine && ScriptEngine().indexOf( 'InScript' ) + 1 ) ||
     ( navigator.vendor == 'KDE' )
    if( !badOldBrowser ) {
      if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //IE 4, 5 & 6 (in non-standards compliant mode)
        xcoord += document.body.scrollLeft;
        ycoord += document.body.scrollTop;
      } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE 6 (in standards compliant mode)
        xcoord += document.documentElement.scrollLeft;
        ycoord += document.documentElement.scrollTop;
      }
    }
  } else {
    //total failure, we have no way of obtaining the mouse coordinates
    return;
  }
  window.alert('Mouse coordinates are ('+xcoord+','+ycoord+')');
}

JavaScript 引用窗口元素

/*
self and window
-> These refer to the global object of current web page.
parent
-> Refers to the window object of the page that is holding the current page in a frameset.
top
-> Refers to the window object of the page at the top of the frames hierarchy.
window.frames[nameOrNumberOfFrame]
-> Refers to a frame or iframe held by the current page.
*/

// -----------------------------
//   frames

window.frames[nameOrNumberOfFrame].window



// -----------------------------
//   breaking out of frame

/*
If someone is loading your page into their frameset and you don't want them to, you can use the self-top relationship to remove your page from their frameset and replace their frameset page with your page using:
*/

if( self != top ) { top.location.replace(self.location.href); }



// -----------------------------
//   hierarchy

parent.frames['otherframename'].document.images['imagename'].src = "sample.gif";



// -----------------------------
//   parent

window.parent.parent.frames['left']
window.top.frames['left']



// -----------------------------
//   forms

reference_to_form.inputname
reference_to_form.elements['inputname']
reference_to_form.elements[number_of_input_(not_image_input)]
document.nameOfForm.mybutton[1]



// -----------------------------
//   selectbox

if( document.myForm.mySelect.selectedIndex == 1 ) {
  document.myForm.mySelect.options[3].selected = true;
  if( !document.myForm.myRadio[1].checked ) {
      document.myForm.myRadio[2].checked = false;
    document.myForm.myRadio[1].checked = true;
    document.myForm.myRadio[0].checked = false;
  }
}



// -----------------------------
//   setting a select option to null will remove 
//   it from the select box

document.forms[number_of_form].mySelect.options[0] = null;



// -----------------------------
//   images

if( document['imagename'].src == "pig.gif" ) {
...
if( document['imagename'].src == myImage.src ) {



// -----------------------------
//   anchors

document.anchors[number_of_<a>_element]
//  if the href attribute is set, you can refer to it using this:
document.links[number_of_<a>_element]

JavaScript DOM树

// gets the element with an id of "MG"
document.getlElementById("Mg").value;

// returns all the div elements as an array
document.getElementsByTagName("div");


// returns the first one of the <p> elements in the array
document.getElementsByTagName("p")[0];

// The root element in HTML <html>...</html>
document.documentElement;

// Creates a new <img> object
document.createElement("img"); 

// now this text node can be added to an element in the markup. 
var favshows = document.createTextNode("24 and Lost"); 


/*
Any change in the browser's model of a web page will automatically update the actual web page in user's browsers
- divNode.parentNode
- divNode.childNodes
- divNode.firstChild
- divNode.lastChild

node      node type      nodeName   nodeValue
div       element        "div"       null
em        element        "em"        null
"abcd"    text           null        "abcd"

Text nodes do not have a nodeName; the node value for an element node is underfined.

Element nodes have a getAttribute() and setAttribute) method. (only elements can have attributes)

Element nodes get the parent and childNodes properties from the Node object. 

If you use a property on a node where that property doesn't apply, you'll get a value like "null" or "undefined"

Every node has a property called nodeType, along with nodeName and nodeValue. The nodeType property returns a number that maps to a value stored in the Node class. 

*/


if (someNode.nodeType == Node.ELEMENT_NODE) { 
  ...
} else if (someNode.nodeType == Node.TEXT_NODE) {
  ..
}

/*
Note tha tsome browsers don't recognize Node.ELEMENT_NODE and report an error. <em>In other words, avoid using it</em>.
*/

JavaScript validaFormulario(OBJ)

function validaFormulario(obj){
	//obj = document.forms[0];
	var errores = new Array();
	with (obj){

		if(nombre.value==""){
			errores.push("- El campo "<strong>Nombre</strong>" es obligatorio.");
		}
		
		if(apellidos.value==""){
			errores.push("- El campo "<strong>Apellidos</strong>" es obligatorio.");
		}
		
		if(cod_postal.value==""){
			errores.push("- El campo "<strong>Código Postal</strong>" es obligatorio.");
		}
		
		if(sexo[0].checked==false && sexo[1].checked==false){
			errores.push("- El campo "<strong>Sexo</strong>" es obligatorio.");
		}
		
		e=email.value;
		if( (e=="") || (e.indexOf("@")==-1 || e.indexOf(".")==-1) ){
			errores.push("- El campo "<strong>Email</strong>" es obligatorio.");
		}

		if(condiciones.checked==false){
			errores.push("- Si desea registrarse, por favor acepte las <strong>condiciones de uso</strong> marcando la casilla correspondiente.");
		}
	
	}

	if (errores.length > 0){
		var mensajes = "Por favor, corriga los siguientes errores:<br><br>";
		for(var i=0; i<errores.length; i++){mensajes += errores[i]+"<br>";}
		var errores = document.getElementById("errores");
		errores.innerHTML = mensajes;
		errores.style.display = "block";
		document.location.href = "#errores";
		//alert(mensajes);
		return false;
	}else{
		var errores = document.getElementById("errores");
		errores.innerHTML = "";
		errores.style.display = "none";
	}
}

JavaScript 自动PULLQUOTES

/*
pullquote function by Roger Johansson, http://www.456bereastreet.com/
*/
var pullquote = {
	init : function() {
	// Check that the browser supports the methods used
		if (!document.getElementById || !document.createElement || !document.appendChild) return false;
		var oElement, oPullquote, oPullquoteP, oQuoteContent, i, j;
	// Find all span elements with a class name of pullquote
		var arrElements = document.getElementsByTagName('span');
		var oRegExp = new RegExp("(^|\\s)pullquote(\\s|$)");
		for (i=0; i<arrElements.length; i++) {
	// Save the current element
			oElement = arrElements[i];
			if (oRegExp.test(oElement.className)) {
	// Create the blockquote and p elements
				oPullquote = document.createElement('blockquote');
				oPullquote.className = oElement.className
				oPullquoteP = document.createElement('p');
	// Insert the pullquote text
				for(j=0;j<oElement.childNodes.length;j++) {
					oPullquoteP.appendChild(oElement.childNodes[j].cloneNode(true));
				}
				oPullquote.appendChild(oPullquoteP);
	// Insert the blockquote element before the span elements parent element
				oElement.parentNode.parentNode.insertBefore(oPullquote,oElement.parentNode);
			}
		}
	},
	// addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	addEvent : function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener( type, fn, false );
		else if (obj.attachEvent)
		{
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
			obj.attachEvent( "on"+type, obj[type+fn] );
		}
	}
};

pullquote.addEvent(window, 'load', function(){pullquote.init();});

JavaScript 设置选择列表到值

function setSelectListToValue(value, selectId){
	var i, si, v, args=setSelectListToValue.arguments;
	if ((obj=document.getElementById(args[1])) != null){
		v = args[0];
		for(i=0; i<obj.length; i++){
			if(obj.options[i].value == v){
				si = i;
			}
		}
		obj.selectedIndex = si;
	}
}