trade html da li

Asked

Viewed 114 times

0

I have a ajax jquery that will receive the click of a href with a figure within.

I wanted to make sure that only during the execution of ajax to image background of li, and not of href was changed and at the end of the operation returned to normal.

That is, the href receives click,. But a li with a image inside is not clicável normally

I’m doing like this:

// JavaScript Document
$(document).ready(function(e) {

  $("a.excluiPlano").click(function() {

      if (confirm('Deseja Excluir este Plano?\nAtenção: Excluindo esse plano, todas as fotos serão excluidas!\nDeseja prosseguir?') ) {

        $.ajax({
            url: "../_requeridos/excluiPlano.php",
            type: 'POST',
            data: {'planoid': $(this).attr('planoid')},
            beforeSend: function() {               
              $("a.excluiPlano").html("<img src='../_img/_bannerImgs/spinner.gif' />")
              return false;
            },
            success: function (retorno) {

                if (retorno == 1) {

                    alert('Excluido com sucesso');
                    location.reload();

                } else {

                    alert("Erro na exclusão");

                }

            },
            cache: false,
            /* REMOVIDAS PARA QUE O AJAX ENVIE VARIÁVEIS FORA DO FORM/
            contentType: false,
            processData: false
            */
        });

        return false;

      }

  })


});

How to do this?

HTML + PHP

<?php 
      $planos = $planosDao->pesquisaPlanos();

      $planosConta = $planos == NULL ? 0 : count($planos);  
?>

<div class="lista">

 <h1 class="titulos">Listagem de Planos</h1>

 <?php 
   if ($planosConta==0) {

       echo $phpUtil->erro ("Sem retornos para esta pesquisa"); 

    } else { 

      $registros = 15; 
      $pagina = (isset($_GET['pagina']))? $_GET['pagina'] : 1; 
      $numPaginas = ceil($planosConta/$registros); 
      $inicio = ($registros * $pagina) - $registros; 

      $where = " LIMIT ".$inicio.",".$registros;
      $planos = $planosDao->pesquisaPlanos($where); 
?>

 <ul class="listaTopo">
     <li style="width:20%">NOME</li>
     <li style="width:55%">DESCRIÇÃO</li>
     <li style="width:10%">EDITAR</li>
     <li style="width:10%">EXCLUIR?</li>
 </ul>
 <?php 

   $contaLinhas = 0;
   $numreg = 25; // Quantos registros por página vai ser mostrado    
   $pagina = isset($_GET["pagina"]) ? $_GET["pagina"] : 1;
   $inicial = ($pagina * $numreg) - $numreg;   

   foreach ($planos as $plano) : 

     $corLinha = $contaLinhas % 2 == 0 ? "rgb(204,204,204)" : "rgb(255,255,255)";

     $linkEditar = "<a href='?editar&idPlano=".$plano->getIdPlano()."'><img src='_img/editar.png' /></a>";

    $linkExcluir = "<a class='excluiPlano' planoid=".$plano->getIdPlano()."><img src='_img/excluir.png' /></a>";

  ?>  
     <ul class="listaRegistros" style="background-color:<?php echo $corLinha; ?>">
         <li style="width:20%; text-align:left;"><?php echo $plano->getNome(); ?></li>
         <li style="width:55%; text-align:left;"><?php echo substr($plano->getDescricao(),0,30)." ..."; ?></li>
         <li style="width:10%; text-align:center;"><?php echo $linkEditar; ?></li>
         <li style="width:10%; text-align:center;" class="excluirRegistro"><?php echo $linkExcluir; ?></li>
     </ul>

 <?php 
   $contaLinhas++;
   endforeach;      

    //exibe a paginação 
    for($i = 1; $i < $numPaginas + 1; $i++) { 
        echo "<a class='contador' href='?listar&pagina=$i'>".$i."</a>"; 
    } 
  } 
?>
</div>
<br />

A simpler example of what I want would be the following:

$(document).ready(function(){
    $('a').click(function(){
        var i = $('a').index(this);
        alert(i);
    });
});
<script type="text/javascript"   src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">link 1</a>
<a href="#">link 2</a>
<a href="#">link 3</a>

With this code I have returned only the element to which received the click.

Now how to get the html() his?

  • What do you call href is an element <a>? You want to click on one <a> that is inside a <li>, an ajax request is made and during this process (until receiving the response from the server) an image is shown in a <li>?

  • Use the beforeSend from ajax to change to what you want and the done to get back to normal

  • Did you see the code posted? In the <code>a</code> element there is an image that represents deletion. What I want is that, during the ajax process, this image changes to an image of Upload and after deletion/ blocking (I will do in 2), go back to normal! That is, the lock image. Because the delete image will no longer be possible because the record will no longer exist! And yes, I used beforeSend. But still all the images changed together

1 answer

0

From what I understand, the problem lies in changing the background image of a li during the the AJAX request process that is executed when a descending element <a> receive a click.

For this, you can use the function css jQuery and the properties beforeSend and complete of function ajax jQuery - if you want, see the documentation here to css and here for the two properties.

$("a.list__link:not(.list__link--not-clickable)").on("click", function(event) {
   event.preventDefault(); // Impede que o browser execute "normalmente" o evento click de uma âncora
   
   //var $elem = $(this).closest("li.list__item"); Pega o `li` ascendente
   var $elem = $(this); // ancora que foi clicado
   var url = $(this).attr("href");
	 var imgUrl = $(this).attr("data-img-url")
	ajaxCall(url, $elem, imgUrl);
});

function ajaxCall(url, $elem, imgUrl) {

   $.ajax({
	 	 url: url,
		 type: 'post',
		 beforeSend: function () {
				$elem.css({"background-image":"url("+imgUrl+")"})
		 },
		 complete: function () {
				$elem.css({ "background-image" : "none" });
		 }
	 });
}

$("a.list__link.list__link--not-clickable").on("click", function (event) {
   event.preventDefault();
   alert("I'm not clickable."); // apagar isto.
});
a.list__link {
  display: block;
  width: 70%;
  height: 70%;
	text-decoration: none;
  background-color: #aaa;
	background-size: 100% 100%;
}
a.list__link.list__link--not-clickable {
 cursor: default;
}

ul.list {
	list-style-type: none;
}

li.list__item {
	height: 15vh;
	width: 80%;
	border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
     <li class="list__item"><a class="list__link" href="item1.html" data-img-url="https://s19.postimg.cc/4khrr69kz/img_1.png">Click me - Item 1</a></li>
     <li class="list__item"><a class="list__link list__link--not-clickable" href="item2.html" data-img-url="https://s19.postimg.cc/jggays0f7/img_2.png">Click me - Item 2</a></li>
     <li class="list__item"><a class="list__link" href="item3.html" data-img-url="https://s19.postimg.cc/kvhvnhtsj/img_3.png">Click me - Item 3</a></li>
     <li class="list__item"><a class="list__link list__link--not-clickable" href="item4.html" data-img-url="">Click me - Item 4</a></li>
 </ul>

  • That’s not it yet. The image changes. But it changes everyone because everyone has the same .class. It’s hard to get the value of his id

  • This feat should occur only for some a?

  • only to the one that was clicked although all have the same class. Take a look at the html please

  • The image should be shown in a and not in the li?

  • this, I need to know then which of this 'a' was the clicked

  • I changed the answer to change the a when this is clicked and created a resource that elements a who possess the class list__link--not-clickable cannot be clicked (when a function is clicked it will be invoked and as it only prevents the "normal" execution of the click, nothing will happen).

  • found that by making a = $("a.excluiPlano"). index(this);, I get the clicked element.Now how do I get the planoid property from it? with attr did not work

  • Inside the function invoked by the click event, you can get the clicked element like this $(this) because this will reference the JS object of the clickable element. To take its property within this function: $(this).attr("planoid").

  • but in case, this will all be having the same class. I’ll add an example of what I need at the end of the question

  • The click event is assigned to all objects selected by the specified selectors - eg: $("a.excluiPlano") selects all elements<a class="excluiPlano">.But when the event is triggered to an object,ouseja,the user clicks on a link,the function invoked, Event Handler,is that passed as an argument for theon-ex: $("a.excluiPlano").on("click",function () {/* Essa é a event handler */ }) -and within it,thiswill reference only the clicked object More about this MDN.

  • So when a link triggers the click event, the function will be executed only for it.

Show 6 more comments

Browser other questions tagged

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