Reputation: 31
My book shows the difference between javascript and jquery but neither script works. Can I see both work?
<!DOCTYPE html>
<html>
<head>
<style type="text/css" src="myCss.css"></style>
<script>
(function(document){
document.onload = function(){
content.style.display = "block";
}
var listItems = document.getElementsByTagName("li");
for(i = 0; i < listItems.length; i++){
listItems[i].onclick = function{
listItems[i].style.backgroundColor = "green";
}
}
})( document );
</script>
</head>
<body>
<ul id="content" class="contentClass">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style type="text/css" src="myCss.css"></style>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$( "#content" ).show();
$( "li" ).click(function(this){
this.css( "backgroundColor","green" );
});
});
</script>
</head>
<body>
<ul id="content" class="contentClass">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</body>
</html>
I tried to do modicfiche on both but I have not solved. I found parentheses going badly, awkward posture of the script.
Upvotes: 2
Views: 931
Reputation: 4288
jQuery, try with:
$("li").on('click', function(){
$(this).css("backgroundColor", "green");
});
Native js:
for(i = 0; i < listItems.length; i++){
listItems[i].onclick = function{
this.style.backgroundColor = "green";
}
}
Upvotes: 4
Reputation: 30557
For the javascript version,
()
after function
or its a syntax error.this
instead of listItems[i].style
because then you have to correctly make a closure to pass in the i
and that is the more complicated route. this
in the click handler will refer to the clicked li
itself(function(document){
document.onload = function(){
content.style.display = "block";
}
var listItems = document.getElementsByTagName("li");
for(i = 0; i < listItems.length; i++){
listItems[i].onclick = function(){
this.style.backgroundColor = "green";
}
}
})( document );
<ul id="content" class="contentClass">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
For the jQuery version,
this
in to the click handler$(this)
instead of this
because you are calling a jQuery function css()
and need the jQuery object( $(this) )$(document).ready(function(){
$( "#content" ).show();
$( "li" ).click(function(){
$(this).css( "background-color","green" );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul id="content" class="contentClass">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
Upvotes: 4
Reputation: 25527
use
$("li").click(function() {
$(this).css("background-color", "green");
});
Upvotes: 2