• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 736
  • Last Modified:

jQuery: Passing i++ to click(function(){})

How can I pass the value for i from my while to a function on click?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Title</title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script type="text/javascript"> 
 
$(document).ready(function(){
 $('a').each( 
  function(){
   var i=0; while (i++ <4){ 
    if(this.href.indexOf('i'+i) > -1) { $(this).click(function(){alert('Change color of link '+i);$('#i'+i).css('color', '#ff0000');});} 
   }
 }); 
});

</script> 
 
</head> 
<body> 
<div>  
  <h1 id="i1">Item 1</h1> 
  <h1 id="i2">Item 2</h1> 
  <h1 id="i3">Item 3</h1> 
  <h1 id="i4">Item 4</h1> 
  <p> 
   <a href="#i1">Link 1</a> 
   <a href="#i2">Link 2</a> 
   <a href="#i3">Link 3</a> 
   <a href="#i4">Link 4</a> 
  </p> 
</body> 
</html>

Open in new window

0
hankknight
Asked:
hankknight
2 Solutions
 
mahomeCommented:
You do! pass the i to the click function. Your problem is that when click-event is called the variable i is 5 and the old values are overriden. So you have to find another way to solve. I attached a solution for your example. In common: You need to extract your information out of the HTML and not out of a JavaScript variable, because this variable changes.

$(document).ready(function(){
 $('a').each( 
  function(){
   var i=0; while (i++ < 4){ 
    if(this.href.indexOf('i'+i) > -1) { 
        $(this).click(function(){
            var current = this.href.substring(this.href.indexOf('#i') + 2);
            alert('Change color of link '+ current);
            $('#i'+i).css('color', '#ff0000');
        });
    } 
   }
 }); 
});

Open in new window

0
 
hieloCommented:
the .each() already passes an index to its function argument as the first parameter. You can use that instead of the while:
$(document).ready(function(){
	$('a').each(function(idx){
		$(this).bind('click',function(){
			var i=1+idx;
			alert('Change color of link '+i);
			$('#i'+i).css('color', '#ff0000');
		})
	})
});

Open in new window

0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now