JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

15.2.1 Selecting Elements By ID

15.2.1 Selecting Elements By ID


Any HTML element can have an idattribute. The value of this attribute must be unique within the document—no two elements in the same document can have the same ID. You can select an element based on this unique ID with the getElementById() method of the Document object. We’ve already used this method in both Chapter 13 and Chapter 14 :

var section1 = document.getElementById("section1");

This is the simplest and most commonly used way to select elements. If your script is going to manipulate a certain specific set of document elements, give those elements id attributes, and look up the Element objects using that ID. If you need to look up more than one element by ID, you might find the getElements() function of Exam ple 15-1 useful.

Example 15-1. Looking up multiple elements by ID

/**

*This function expects any number of string arguments. It treats each*argument as an element id and calls document.getElementById() for each.*Returns an object that maps ids to the corresponding Element object.*Throws an Error object if any of the ids is undefined. */

function getElements(/*ids...*/) {

var elements = {}; // Start with an empty map

for(var i = 0; i < arguments.length; i++) { // For each argument

var id = arguments[i]; // Argument is an element id

var elt = document.getElementById(id); // Look up the Element

if (elt == null) // If not defined,

throw new Error("No element with id: " + id); // throw an error

elements[id] = elt; // Map id to element

}

return elements; // Return id to element map

}

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31423.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1