0

I try run the following code in Firefox 27.0.1 and Chrome 30.0.1599.114 on a machine with Kubuntu Linux, and nothing happens.

The html page is part from a web application based on Spring MVC framework, and was placed in the folder WEB-INF/jsp. Someone can find any error in the code below?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>HorarioLivre</title>

  <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
  <script>
  $('a').click(function() {
      alert("clicou em um link");
  });
  </script>

  <link rel="stylesheet" href="css/style-main.css">
  <link rel="stylesheet" href="css/style-popup.css">
</head>
<body>
  <header>
    <div class="container">
      <h1><a href="#">HorarioLivre</a></h1>
      <nav>
        <ul>
          <li><a href="listagem_evento.html" class="icon evento">Eventos</a></li>
          <li><a href="cadastra_horario.html" class="icon horario">Cadastrar Horarios</a></li>
          <li><a href="listagem_horario.html" class="icon horario">Listar Horarios</a></li>
          <li><a href="listagem_usuario.html" class="icon usuario">Usuarios</a></li>
          <li><a href="#">${usuario.nome}</a>
            <ul>
                <li><a href="usuario_perfil.html" class="icon perfil">Perfil</a></li>
                <li><a href="usuario_config.html" class="icon settings">Configura&ccedil;&otilde;es</a></li>
                <li><a href="#">Logout</a></li>
            </ul>
          </li>
        </ul>
      </nav>
    </div>
  </header>
  <div id="results">
        <a href="#" id="close">Fechar</a>
        <div id="content"></div> 
  </div>
</body>
</html>
Kleber Mota
  • 8,521
  • 31
  • 94
  • 188

3 Answers3

3

You don't say what your "errors" are, but my guess is you've left out the document ready handler, so by the time your selector is run, the elements are not ready in the DOM yet.

$(function() {
  $('a').click(function() {
      alert("clicou em um link");
  });
});
Mitya
  • 33,629
  • 9
  • 60
  • 107
1

You need to wrap your code inside DOM ready handler $(document).ready(function() {....}) or shorter form $(function() {.... }) to make sure all of your elements are properly added to the DOM before executing your jQuery code.

$(function() {
    $('a').click(function() {
        alert("clicou em um link");
    });
});
Felix
  • 37,892
  • 8
  • 43
  • 55
1

You are selecting all the a elements that exist at the time the script runs (all zero of them since the script runs in the head and all the a elements exist in the body) and doing stuff to them.

Move the script to just before </body> or create a function and run it on DOM ready.

jQuery(function () {
    $('a').click(function() {
        alert("clicou em um link");
    });
});

… then there will be actual a elements you can manipulate.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335