Picking up data via ajax

1

I need to get content from a div. I'm actually building a dynamic menu, where I define

<li class="menuLi">
  <div class="acao">-3</div>
  <div class="desc">Inicio</div>
</li>

Then I have an ajax that should take this acao and send it to a page to know which page it will load. But when I get this action it is not coming, the attribute comes as undefined .

The code js.

function carregarPaginas() {
    $(".menuLi").click(function (e) {
        e.preventDefault();
        var acao = $(this).attr('href');
        location.href = 'includes/publicacao.php?c='+acao;
    });
} 
    
asked by anonymous 09.07.2015 / 22:13

4 answers

4

You are not using a link in% s of%, so it is not possible to get the <li> attribute.

  • It is recommended that you assign the event href to click to .menuLi of the document.
  • Because it is registering a ready , it should not be inside a function, since the function will "bind" several times the same event, so no bind of class click within a function but directly in .menuLi of document.
  • Conclusion

    Your HTML

    <li class="menuLi">
      <div class="acao">-3</div>
      <div class="desc">Inicio</div>
    </li>
    

    The correct JavaScript:

    $(document).ready(function() {
          $(".menuLi").click(function (e) {
            e.preventDefault();
    
            var acao = $(this).children('.acao').html();
            location.href = 'includes/publicacao.php?c='+acao;
        });
    });
    

    JSFIDDLE

        
    09.07.2015 / 23:47
    1

    $("#menu li a").click(function() {
      var resposta = $(this).attr('href');
      alert(resposta);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script><ulid="menu">
      <li><a href="login.html"> Login</a>
      </li>
      <li><a href="menu.html"> Menu</a>
      </li>
    </ul>
        
    09.07.2015 / 22:42
    0

    If your intention was to get the action defined in the first internal div of the selected menu, then just replace var acao = $(this).attr('href'); with

    var acao = $(this).find(".acao").text();
    
        
    10.07.2015 / 02:36
    0

    Oops, try this:

    var acao = $(".acao").html();
    
        
    10.07.2015 / 15:35