官术网_书友最值得收藏!

Finding an element by its ID attribute

This cross-browser method allows us to quickly get a "handle" on our HTML element.

How to do it...

If we imagined a world where we could grab an element with a simple and easy-to-remember syntax just by sending the element's ID attribute, we would be dreaming of MooTools.

<script type="text/javascript"
src="mootools-1.3.0.js"></script>
</head>
<body>
<div id="my_trigger"
style="width:100px; height:100px;
border:1px solid #BEBEBE;
line-height:50px; text-align:center;">You Found Me!</div> <noscript>JavaScript is disabled.</noscript>

Tip

Always include the NOSCRIPT tag, which is omitted going forward only to save space.

<script type="text/javascript">
// raw javascript's familiar method, not cross-browser use
// var my_element = document.getElementByID('my_target');
// MooTools uses the $ object to grab elements by ID
var my_element = $('my_trigger');
var my_element_text = my_element.get('text');
alert(my_element_text);
</script>

Tip

Always include the closing BODY and HTML tags. Also omitted going forward.

 </body> </html>

How it works...

When we use raw JavaScript to get a handle on an element, we either depend on the browser to match our code, or we have to write a mess of browser compatibility to be sure that our user has a browser that supports the JavaScript implementation that we are writing for. MooTools abstracts that cross-browser nightmare and gives us the dollar object $(), an alias for document.id().

Note

Starting with version 1.2, MooTools began to use document.id() to grab elements by ID. This allows MooTools to play nice with other frameworks that extend using the dollar syntax. When using multiple frameworks, do not use the $() alias for document.id().

Pass the dollar or document.id() object the ID for the element to grab, and the object returned is a MooTools-extended object ready to do our bidding through Element methods.

In this example, we use the method get(), which takes a single argument, the property of the object to return. We then alert the var my_element_text to the screen using the raw JavaScript alert() function.

There's more...

This recipe can be easily recreated with a single, easy-to-understand one-liner:

alert($('my_trigger').get('text'));
主站蜘蛛池模板: 运城市| 瓦房店市| 沂源县| 射阳县| 大港区| 岚皋县| 靖远县| 静宁县| 宽甸| 舟山市| 南康市| 军事| 藁城市| 霍林郭勒市| 湟中县| 金坛市| 云安县| 镇沅| 太仓市| 南通市| 定南县| 安阳县| 临桂县| 蒙山县| 高密市| 平阳县| 黎城县| 石林| 淮阳县| 渑池县| 龙岩市| 吉安县| 突泉县| 青阳县| 温州市| 旅游| 泸定县| 建宁县| 汪清县| 教育| 中方县|