Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách thêm phần tử
  • mới vào
      bằng jQuery

  • Để thêm phần tử danh sách mới vào <ul>, dùng phương thức append() của jQuery.

    Thiết lập input type text:

    Giá trị: <input type="text" name="task" id="input">

    Khi click nút, thêm <li> mới dùng val() và append():

    $('button').click(function() {    var mylist = $('#input').val();    $('#list').append('<li>'+mylist+'</li>');    return false; });

    Chạy mã sau để học cách thêm phần tử danh sách bằng jQuery:

    Ví dụ

    <!DOCTYPE html> <html> <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    <script>       $(document).ready(function(){          $('button').click(function() {             var mylist = $('#input').val();                $('#list').append('<li>'+mylist+'</li>');                return false;             });          });    </script> </head> <body>    <form>       Value: <input type="text" name="task" id="input">       <button>Submit</button>       <br>       <p>Nhập giá trị và nhấn Submit để thêm mục mới.</p>       <ul id="list">       </ul>    </form> </body> </html>