What would be the most efficient way to replicate this code? (Javascript)

Asked

Viewed 236 times

0

Doubt

With this code, I can only create and manipulate a "employee", I wanted to be able to add more employees by clicking a button and manipulate their data.

HTML

<!DOCTYPE html>
<html>
    <body>
      Funcionario: <div id="func"></div>
      <button id="alternome">Alterar nome</button>
      Salario: R$<div id="salario"></div>
      <button id="aumenta">+</button><button id="abaixa">-</button>
    </body>
</html>

Javascript

function funcionario(){
//altera div func
var f = document.getElementById("func");
var s2 = f.innerHTML;
f.innerHTML = prompt("Qual o nome do funcionario??");
//pos-alteramento de nome
var a= document.getElementById("alternome");
a.onclick = function alternome(){
    f.innerHTML = prompt("Qual o nome atual?");
}
//altera div salario
var n=document.getElementById("salario");
var s1 = n.innerHTML;
n.innerHTML = prompt("Qual o salario?");

//aumenta valor
var m=document.getElementById("aumenta");
m.onclick = function aumenta(){
    //gambiarra para aumentar o valor 100X
    for(var i=0;i<100;i++){
    n.innerHTML++;
    }
};
//decrementa valor
var o=document.getElementById("abaixa");
o.onclick = function abaixa(){
    //gambiarra para abaixar o valor 100X 
    for(var i=0;i<100;i++){
        if(n.innerHTML==0){
            continue;
        }
    n.innerHTML--;
    }
};
}
//tem q colocar essa função pra funcionar os bagui
setTimeout(funcionario, 500);
  • Hello Mr. We have made suggestions for code. Make sure they help you. If the answer is positive, and mark as solved, or if you liked the answer give an UP to help our reputation.

2 answers

0

I have a code that can help you. This helps in many cases.

Place script after body'.

		// AQUI EU SETO O MÉTODO TEMPLATE
		String.prototype.template = function (obj) {
		    return this.replace(/\{\{([\w]+)\}\}/g, function (str, prop) {
		        return obj[prop];
		    });
		};

		// ESTE É O MODELO QUE VOCÊ IRÁ USAR
		var modelo = '' +
	      'Funcionario: <div id="func">{{nome}}</div>' +
	      '<button id="alternome">Alterar nome</button>' +
	      '<input type="hidden" name="idfunc" id="idfunc" value="{{id}}" />' +
	      'Salario: <div id="salario">R${{salario}}</div>' +
	      '<button id="aumenta">+</button><button id="abaixa">-</button>';

		// ESSE É O JSON, QUE PODER SER RECEBIDO DE UMA REQUISIÇÃO. FICA A DICA
	    var users = [
	        {
	            id      : 1,
	            nome    : "JOAO",
	            salario : 2000
	        },{
	            id      : 2,
	            nome    : "MARIA",
	            salario : 3000
	        }
	    ];

	    // AQUI EU ESCREVO NA DIV
      	users.forEach(function(o, i){      		
      		document.getElementById("funcionarios").innerHTML += modelo.template(users[i]);  			
      	});
<!DOCTYPE html>
<html>
	<head>
		<title></title>
		
	</head>
	<body>
		<div id="funcionarios"></div>
	</body>
	

</html>

0

Turns these Ids into classes once Ids have to be unique on the page. That way you can create a logic relative to the parent element of each employee and

var f = document.getElementById("func");

you can use a class search from the element you want to edit:

var f = el.querySelector('.nome');

I further developed your code for what you asked for and it stayed that way:

function editarFuncionario(el) {
    //altera div func
    var f = el.querySelector('.nome');
    var s2 = f.innerHTML;
    f.innerHTML = prompt("Qual o nome do funcionario??");
    //pos-alteramento de nome
    var a = el.querySelector(".alternome");
    a.onclick = function alternome() {
        f.innerHTML = prompt("Qual o nome atual?");
    };
    //altera div salario
    var n = el.querySelector(".salario");
    var s1 = n.innerHTML;
    n.innerHTML = prompt("Qual o salario?");

    //aumenta valor
    var m = el.querySelector(".aumenta");
    m.onclick = function aumenta() {
        n.innerHTML = (Number(n.innerHTML) || 0) + 100;
    };
    //decrementa valor
    var o = el.querySelector(".abaixa");
    o.onclick = function abaixa() {
        n.innerHTML = (Number(n.innerHTML) || 0) - 100;
    };
}

function removerFuncionario(el) {
    el.parentElement.removeChild(el);
}

function adicionarFuncionario(el) {
    var novo = el.cloneNode(true);
    el.parentElement.appendChild(novo);
    auscultador(novo);
}

function closest(el, selector) {
    while (el && !el.matches(selector)) {
        el = el.parentElement;
    }
    return el;
}

function auscultador(el) {
    var buttons = el.querySelectorAll('.ui-buttons');
    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener('click', function(e) {
            var el = closest(e.target, '.funcionario');
            var action = e.target.dataset.action;
            if (action == 'editar') return editarFuncionario(el);
            if (action == 'remover') return removerFuncionario(el);
            if (action == 'adicionar') return adicionarFuncionario(el);
        });
    }
}

auscultador(document.body);
.funcionario {
    padding: 20px;
}
<div class="funcionario">
    <div> Funcionario:
        <div class="nome"></div>
        <button class="alternome">Alterar nome</button>
    </div>
    <div> Salario: R$
        <div class="salario"></div>
        <button class="aumenta">+</button>
        <button class="abaixa">-</button>
    </div>
    <div class="ui-buttons">
        <button data-action="adicionar">Adicionar novo functionario</button>
        <button data-action="editar">Editar functionario</button>
        <button data-action="remover">Remover functionario</button>
    </div>
</div>

Online example: https://jsfiddle.net/tnehgpd5/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.