click and Hover does not work

Asked

Viewed 59 times

0

Hello, I am developing a project, where I have a click on a div that after clicked is placed or removed a class of an element inside it that makes appear and disappear a cross, but for some reason as soon as I swapped out the static test data for data coming from the API this click stopped working as well as another Hover effect that should in principle come from the same problem. Below in the code you will find this comment "Below this click problem that does not run" is where the problem is. If I put the click function still inside the above ajax only the first div of the button works the remaining ones not.

window.onload = function() {
          $.ajax({
        method: "POST",
        url: "http://2.81.244.98/dns/admin/api.php",
        data: {
            task: "clean"
        }
        });
      $.ajax({
      method: "POST",
      url: "http://2.81.244.98/dns/admin/api.php",
      data: { task: "validatecook", all: true }
    })
      .done(function( msg ) {
        var obj = JSON.parse(msg);
      });
    $.ajax({
      method: "POST",
      url: "http://2.81.244.98/dns/admin/api.php",
      data: { task: "listarSites"}
    })
      .done(function( msg ) {
        var obj = JSON.parse(msg);
        for (var i = 0; i < obj['ids'].length; i++) {
          if(obj['ativos'][i] === "0"){
            var backgroundC = 'class="disable"';
            var rasurado = 'rasurado';
          }else{
            var backgroundC = '';
            var rasurado = '';
          }
          $("#tabela").append('<tr ' + backgroundC + '><td class="espca"><div id="select" data-secid="' + obj['ids'][i] + '"><label class="cruz desativado">X</label></div></td><td class="espca ' + rasurado + '" width="10">' + obj['webpage'][i] + '</td><td class="espca ' + rasurado + '">' + obj['categorias'][i] + '</td><td class="espca"><button><label><i class="fas fa-pencil-alt"></i></label></button></td></tr>');
        }
      });
    	$(".exit").click(function() {
    saida();
    });
      $("#select").hover(
      function() {
        $("#tabela").addClass("noselect");
      }, function() {
        $("#tabela").removeClass("noselect");
      }
    );
     // Em baixo esta o problema do click que não é executado
      $("#select").click(function() {
        $(this).find('.cruz').toggleClass('desativado');
      });
    $(".new").click(function() {
      location.href = "new.html";
    });
    $(".list").click(function() {
      location.href = "painel.html";
    });
    $(".cats").click(function() {
      location.href = "cats.html";
    });
    $(".req").click(function() {
      location.href = "requests.html";
    });

    if(getParameter("opt") != false){
      var opt = getParameter("opt");
    if(opt == "exit"){
          $.ajax({
      method: "POST",
      url: "http://2.81.244.98/dns/admin/api.php",
      data: { task: "logout"}
    })
      .done(function( msg ) {
        var obj = JSON.parse(msg);
        if(obj['res'] == "ok"){
          location.href = "index.html";
        }
      });
      }
    }
    }
     function getParameter(theParameter) {
      var params = window.location.search.substr(1).split('&');
      for (var i = 0; i < params.length; i++) {
          var p = params[i].split('=');
          if (p[0] == theParameter) {
              return decodeURIComponent(p[1]);
          }
      }
      return false;
    }
    function saida(){
      var cnf = confirm("Pretendes realmente sair?");
      if (cnf == true) {
        location.href = 'painel.html?opt=exit';
      }
    }
* {
            margin: 0;
            padding: 0;
            box-sizing:border-box;
        }
        body {
          font-family: Helvetica;
          -webkit-font-smoothing: antialiased;
        }
        ul {
          list-style-type: none;
          margin: 0;
          padding: 0;
          overflow: hidden;
          background-color: #333;
        }
        li {
          float: left;
        }
        li a {
          display: block;
          color: white;
          text-align: center;
          padding: 14px 16px;
          text-decoration: none;
        }
        li a:hover:not(.active) {
          background-color: #111;
        }
        .wellcome{
            background-color: #444;
        }
        .wc{
    padding: 14px 16px;
    font-size: 18px;
    color: white;
    text-align: center;
  }
  .active {
    background-color: #4CAF50;
  }
  .modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 18%;
}
div#regit{
  width: 90%;
  margin: 10px auto;
}
div#regit #tabela{
  table-layout:fixed;
  border-collapse: collapse;
  width: 100%;
  padding: 10px;
}
.espca{
   word-wrap:break-word;
  border-bottom: 1px solid #ccc;
  padding: 10px;
}
.espca button{
  padding: 10px;
  background: transparent;
  border: none;
  font-size: 20px;
  cursor: pointer;
  outline: none;
}
.espca button label{
  cursor: pointer;
}
div#regit #tabela tr:hover:not(.header){
  background: #f3f3f3;
}
div#select{
  cursor: pointer;
  width: 40px;
  background: #FFF;
  height: 40px;
  border: 1px solid #000;
  padding: 10px;
}
.cruz{
  font-size: 18px;
  cursor: pointer;
}
.desativado{
  visibility: hidden;
}
.noselect{
  user-select: none;
}
div#btns button{
  margin-bottom: 12px;
  padding: 10px;
  border: 1px solid #000;
  background: #00b4fa;
  outline: none;
  cursor:pointer;
  font-size: 16px;
  color: #FFF;
  border-radius: 3px;
}
div#btns button:hover{
  background: #09F;
}
div#btns button:not(:first-child) {
    margin-left: 8px;
}
.disable{
  background: #f1f1f1;
}
.rasurado{
  text-decoration: line-through;
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>SMART DNS | Controlo de Bloqueios</title>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" media="all">
</head>
<body>
<div class="wellcome">
<p class="wc"></p>
</div>
<ul>
<li><a class="new" href="javascript:void(0)"><i class="far fa-plus-square"></i> Novo Registo</a></li>
<li><a class="list active" href="javascript:void(0)"><i class="fas fa-list"></i> Lista de Sites</a></li>
<li><a class="cats" href="javascript:void(0)"><i class="fas fa-quote-right"></i> Lista de Categorias</a></li>
<li><a class="req" href="javascript:void(0)"><i class="fas fa-network-wired"></i> Pedidos de Desbloqueios</a></li>
<li style="float:right"><a class="exit" href="javascript:void(0)"><i class="fas fa-sign-out-alt"></i> Sair</a></li>
</ul>
<div id="regit">
<div id="btns">
<button>Selecionar Todos</button>
<button>Remover Selecções</button>
<button>Ativar Itens Selecionados</button>
<button>Desativar Itens Selecionados</button>
<button>Apagar Itens Selecionados</button>
</div>
<table id="tabela">
<tr class="header">
<td class="espca">Selecionar</td>
<td class="espca">Pagina Web</td>
<td class="espca">Categorias</td>
<td class="espca">Editar</td>
</tr>
</table>
</div>
</body>
</html>

  • 1

    add tbm your html so we can simulate what you’re doing

1 answer

1


First, an id must be a single selector, you are adding several elements with the same Id on the screen... Change the id selector to class or select selector of your choice.

Second, when adding the element with Jquery, the . click() function will already be loaded, so the element will not be recognized, add the function .on("click", Handle) to add the event to elements dynamically added to the DOM.

//Removido o Id e adicionado o class="select" à div que necessita o evento
$("#tabela").append('<tr ' + backgroundC + '><td class="espca"><div class="select" data-secid="' + obj['ids'][i] + '"><label class="cruz desativado">X</label></div></td><td class="espca ' + rasurado + '" width="10">' + obj['webpage'][i] + '</td><td class="espca ' + rasurado + '">' + obj['categorias'][i] + '</td><td class="espca"><button><label><i class="fas fa-pencil-alt"></i></label></button></td></tr>');

//Adicionado o evento à classe no lugar do id e alterado a função .click para .on()
$(".select").on("click", function() {
    $(this).find('.cruz').toggleClass('desativado');
});

Browser other questions tagged

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