Home>
I created a program that displays values ​​when I click the

tag.
If i create about 10 tags, you will have to write the same process 10 times.
(Current source code is only 3)

I want to use JQUERY's each statement, but I can't write it well.
Please give me some advice.

Applicable source code
<html>
<head>
<title>JavaScript test</title>
<script src = "http://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <script>
        $(function () {
            $('li'). each (function (i) {
                $("li"). click (function () {
                    alert (id);
                });
            });
        });
    </script>
</body>
</html>
  • Answer # 1

    It's awkward to set for each id.
    This can be done by displaying the contents of the id attribute when the<li>tag is clicked.

    Addendum

    Oh, it's solved. . .
    jQuery does not know the need to use each even though it can be done in 3 lines.

    $('li'). click (function () {
      alert ($(this) .get (0) .textContent)
    })

  • Answer # 2

      If you create about 10

    tags, you will have to write the same process 10 times.

    Do you think it's awkward to have to bother with id in html?
    No need to use each ...

    <! DOCTYPE HTML>
    <html lang = "en">
        <head>
            <meta charset = "UTF-8">
            <title></title>
        </head>
        <body>
            <ul>
                <li>10</li>
                <li>20</li>
                <li>30</li>
                <li>40</li>
            </ul>
            <script type = "text/javascript" src = "// code.jquery.com/jquery-3.1.1.min.js"></script>
            <script type = "text/javascript">
                $(function () {
                    $('ul>li'). on ('click', function () {
                        alert ($(this) .text ());
                    });
                });
            </script>
        </body>
    </html>

  • Answer # 3

    If you write js described in.each (), it looks like this.

    $(function () {
       $('li'). each (function () {
          $(this) .click (function () {
             alert ($(this) .html ());
          });
       })
    });