Question

basically my problem is the following:

  1. I have N div.
  2. with .each() function I have setup a setInterval() function on these div (example: change the html content).
  3. With a button (one button for each div) I can remove the div.

Problem: if the div are, for example, 5 and I remove one of them with the jquery command: .remove() the .each() keep iterate for 5 div.

How can I fix it? Thx. FIDDLE: http://jsfiddle.net/Alberto_Ar3s/Yr8UP/

for fiddle haters...

html

<div id='a1' class='clue'>a1
    <input type='button' class='remove' value='del' data-id='a1'>
</div>
<div id='a2' class='clue'>a2
    <input type='button' class='remove' value='del' data-id='a2'>
</div>
<div id='a3' class='clue'>a3
    <input type='button' class='remove' value='del' data-id='a3'>
</div>
<div id='a4' class='clue'>a4
    <input type='button' class='remove' value='del' data-id='a4'>
</div>
<div id='a5' class='clue'>a5
    <input type='button' class='remove' value='del' data-id='a5'>
</div>

js

var $j = jQuery.noConflict();

$j(function () {

    $j('.clue').each(function () {
        var id = $j(this).attr('id');
        setInterval(function () {
            console.log('id: ' + id);
        }, 1000);
    });

    $j('.remove').click(function (e) {
        e.preventDefault();
        var dtd = $j(this).attr('data-id');
        $j('#' + dtd).remove();
        return false;
    });

});
Was it helpful?

Solution

The .each() does not continue to iterate, it's the setInterval which logs every second. You need to clear the interval or wrap the each with setInterval.

setInterval(function () {
    $j('.clue').each(function () {
        var id = $j(this).attr('id');// or use this.id
        console.log('id: ' + id);
    });
}, 1000);

DEMO

Edit: Also as @A. Wolff noted in the comments this will avoid setting multiple useless intervals, using only one

OTHER TIPS

The

.each

is executed only once. Problem is, you start the interval for every one of the five divs and it gets executed forever, if you not stop them. You need to stop the interval for the deleted div.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top