I am learning JavaScript event my point is that ' this
' keyword is used for object or global object but in this code this keyword is used in element in function callback parameter why ?
Q1) How we can use 'this' in element onClick
event in this code ?
Q2) Secondly sometime i put this keyword in function argument parameter so error generate ' Unexpected Token
'.
Kindly help for these two question.
HTML CODE:
<!DOCTYPE HTML>
<html>
<body>
<link type="text/css" rel="stylesheet" href="example.css">
<div class="d1" onclick="highlight(this)">1
<div class="d2" onclick="highlight(this)">2
<div class="d3" onclick="highlight(this)">3
</div>
</div>
</div>
<script>
function highlight(elem) {
elem.style.backgroundColor='yellow'
alert(elem.className)
elem.style.backgroundColor = ''
}
</script>
</body>
</html>
Q1) How we can use 'this' in element onClick event in this code ? A)'this' in HTML refers to the HTML element that received the event.in your case the element is 'div'
Q2) Secondly sometime i put this keyword in function argument parameter so error generate 'Unexpected Token'. A) i see 'this' is an implicit param that will be passed automatically when we call a function based on the object , the function call is attached to . so i feel , there will be a conflict b/w function argument's 'this' & implicit 'this'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.