English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I'm trying to use "this" to reduce the amount of functions I need to write. I know I can use this.src="so and so" in an event inside an element, but what about in the script defined in the head?

2006-09-20 15:33:12 · 3 answers · asked by Rockstar 6 in Computers & Internet Programming & Design

3 answers

"This" refers to the object for which its contained, this can include an event, in which case "this" refers to the event object. First you must add a listener to an object, or you could say "attach an event". See the below code

//
// document.getElementById is used to assign the element
// by ID
function doLoad()
{
// the below code has been modified by Yahoo!
// it should read "document dot getlementbyid ('myLink') dot
// onclick = funcRef;"
document.getElementById("myLink").onclick = funcRef;
}
function funcRef()
{
// this will now refer to the element associated to the event
this.style.color = "red";
}
// its important to note that you cannot assign an element
// using document.getElementById until the page has fully
// rendered. So, we will attach doLoad to the onload event
window.onload = doLoad;
// all of the above code should reside in the head
// the code below should reside in the body
i turn red

//
Hope this helps

2006-09-20 18:14:48 · answer #1 · answered by jnicora2002 2 · 0 0

What are you trying to use this.src for? this.src only works for images (img src=...).

You can implement JavaScript in the head and use functions with "this".

Outside the function area you can also use "this" but it would usually refer to the document unless "this" was defined beforehand.

2006-09-20 15:40:58 · answer #2 · answered by Robin C 4 · 0 0

I don't think that there is any relationship between the JS keyword "this" and the DOM. You use "this" to refer to the current object.

2006-09-20 16:37:03 · answer #3 · answered by sterno73 3 · 0 0

fedest.com, questions and answers