1
var id=100;

for(var i=0;i<5;i++) {
 $("#divtext_"+id).click(function(e) {
   onClicked();
 });
}

function onClicked() {
  alert("Clicked")
}
  • I tried with .on() , delegate(), and one() events.
  • When I clicked div, the onClicked() function gave an alert() 4 times.
  • Is it possible when I click div text/image to get one time function/alert?
Fraser
  • 15,275
  • 8
  • 53
  • 104
user3599212
  • 429
  • 2
  • 6
  • 18
  • `for(var i=0;i<2;i++){` – underscore May 03 '14 at 14:10
  • 1
    You use variable `id` in your loop, that does not change. Did you intend to use `i` in your loop? Currently you set handler for the same component in each iteration, so it fires 4 times. – Eadel May 03 '14 at 14:11

4 Answers4

0

This is how I would expect the code to run under jquery, the options here would be to either use .unbind (http://api.jquery.com/unbind/) to remove all previous instructions for this div or to check if the event has already been bound, this has been covered here. How to check if click event is already bound - JQuery

Community
  • 1
  • 1
andyd_28
  • 161
  • 6
0

Presuming you have divs with IDs divtext_0 ... divtext_4

for(var i=0;i<5;i++) {
 $("#divtext_"+i).click(function(e) {
   onClicked();
 });
}

function onClicked() {
  alert("Clicked")
}

At the moment you are adding multiple click handlers to the div divtext_100 - rather than adding one click handler to multiple divs.

It is hard to say what is best without seeing your HTML - but if you gave all your divs a class, e.g. 'clickable', then you can avoid any loops and make any div with that class clickable.

<div class="clickable"></dvi>

You could simply do.

$(".clickable").click(function(e) {
  onClicked();
});

function onClicked() {
  alert("Clicked")
}
Fraser
  • 15,275
  • 8
  • 53
  • 104
  • my div id having single id i.e **divtext_100**, actually in my project `$("#divtext_"+id).click(function(e) { onClicked(); });` is in reload function we did not used for loop, example i written for loop instant of reload function. that reload function call click event every 20 seconds. – user3599212 May 03 '14 at 14:51
  • if i click after 40 seconds i get two alerts, and wait for 60 seconds then i clicked it s given 3 alerts. – user3599212 May 03 '14 at 14:56
  • Sorry - I have no idea what you are talking about. If you have code that is causing a problem you should include it in the question. – Fraser May 08 '14 at 07:46
0

try this:

$("#divtext_"+id).one("click", function(e){
  onClicked();
});
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
ravi
  • 161
  • 10
0

You can use $("#divtext_"+id).off('click',onClicked).on('click',onClicked);

function onClicked() {
    alert("Clicked")
}

'.off' prevents binding of onClicked function multiple times. I think using .off will solve your problem. If you are using older version of jquery then use .unbind.

Harshit Jain
  • 492
  • 3
  • 8