Javascript: calling the same function at the same time?

I am developing this awhile javascript code that it only runs one function when a button is clicked.

JAVASCRIPT:

var a = 1;

function add(name) 
{
if (a <= 9) 
    {
        a++;
        var parent = name.parentNode;
        var content = parent.querySelector("div");
        var str = content.innerHTML;
        str = str.replace(/_1/gi, '_' + a);
        var divtest = document.createElement("div");
        divtest.setAttribute("id", a);
        divtest.innerHTML = str + a;
        parent.appendChild(divtest);
    }
}   

      

HTML:

<div id="main1">
<button onclick="add(this);return false;">+</button>
<div id="content1">
A
</div>
</div>

<div id="main2">
<button onclick="add(this);return false;">+</button>
<div id="content2">
B
</div>
</div>

      

The above code only calls the function once, but I want it to run the function at the same time.

OUTPUT:

+
A
A 2
A 3
A 4
A 5
A 6
A 7
A 8
A 9
A 10
+
B

      

When I click on the button on both divs, it should add both main divs per click.

EXPECTED OUTPUT:

+
A
A 2
A 3
A 4
A 5
A 6
A 7
A 8
A 9
A 10
+
B
B 2
B 3
B 4
B 5
B 6
B 7
B 8
B 9
B 10

      

+3


source to share


1 answer


Assuming the code works, this is simple enough:

function add(me) 
{
    var buttons = document.querySelectorAll('button.add');
    var btn;
    for(var b = 0; b < buttons.length; b++)
    {
        btn = buttons[b];
        if(me === btn) {
            btn.a = btn.a || 1;
            btn.a++;
            addForButton(btn);
        }
    }
}

function rem(me) 
{
    var buttons = document.querySelectorAll('button.remove');
    var btn;
    for(var b = 0; b < buttons.length; b++)
    {
        btn = buttons[b];
        if(me === btn) {
            var divs = me.parentNode.querySelectorAll('div > div');
            if(divs.length > 1){
                divs[divs.length - 1].parentNode.removeChild(divs[divs.length - 1]);
                btn.a--;
            }
        }
    }
}

function addForButton(name) {
    var parent = name.parentNode;
    var content = parent.querySelector("div");
    if (name.a <= 9) 
    {
        var str = content.innerHTML;
        str = str.replace(/_1/gi, '_' + name.a);
        var divtest = document.createElement("div");
        divtest.setAttribute("id", name.a);
        divtest.innerHTML = str;
        parent.appendChild(divtest);
    }
}

      



Then add IDs to the buttons:

<button onclick="add();return false;">+</button>

<button onclick="add();return false;">+</button>

      

+2


source







All Articles