0

I want change somethings after click events, but I need use while loop for make short code.

for example:

$('#DIV1').click(function() {
  // DoSomething     
}
$('#DIV2').click(function() {
  // DoSomething
}

use while loop for that

var i = 1; var ExapmleVar
while(i < 5)
{
 $('#DIV' + i).click(function() {
  ExapmleVar = i; 
 }
}

in the result ExapmleVar = 6 it's not true for me i want ExampleVar equal to 1 in first loop and equal to 2 in second loop and etc

1
  • While is not your solution. State you exact problem, otherwise in my experience the question is good candidate for What is the XY problem? Commented Mar 16, 2015 at 12:10

3 Answers 3

2

create event using fix prefix operator . here div[id^=DIV] assign click event to add div element which have id with prefix 'DIV'. $(this).index() return index of that element in a group of divs whit id is stat with 'DIV'

 $('div[id^=DIV]').click(function() {
  // DoSomething  
   ExapmleVar = ($(this).index() + 1);   
 }
Sign up to request clarification or add additional context in comments.

4 Comments

It will not work in case if any other element is present in between $('div[id^=DIV]')
please explain a little, I want use it for id(s) can i write like this: $('#divid[id^=divid])?
@MojtabaSh $('div[id^=DIV]') .. div is element and DIV as per your example prefix for each div id like DIV1, DIV2 DIV3 . so this $('div[id^=DIV]') assing event to all divs which have id started with DIV.
@MojtabaSh check my updated answer . i have added some explanations regarding $('div[id^=DIV]')
0

use id starting with selector

$('div[id^=DIV]').click(function() {

Documentation here

or

   $('className').click(function() {

Comments

0

Looping is bad practice in that case, You can use class instead like,

$('.common-class').click(function(){
   ExapmleVar = $('.common-class').index(this)+1;
});

$('.common-class').click(function(){
   alert($('.common-class').index(this)+1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="common-class">1</div>
<div class="common-class">2</div>
<div class="common-class">3</div>
<div class="">Not common. Yeah!</div>
<div class="common-class">4</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.