Dùng data-role và id

Trong bài Phân vùng với jQuery Mobile, chúng ta đã làm quen với thuộc tính data-role giúp việc phân vùng hiệu quả hơn với jQuery Mobile. Thuộc tính data-role cũng hữu ích trong việc thêm nhiều trang đến cùng một tập tin HTML nhờ jQuery Mobile. Xem ví dụ tập tin test.html chứa hai trang homePageaboutPage:


<html>

   <head>

         <title>First Mobile Example</title>

         <meta name="viewport" content="width=device-width, initialscale=1">

   </head>

   <body>

     <div data-role="page" id="homePage">

        <div data-role="header">Welcome</div>

          <div data-role="content">

            <p>

             Welcome to our first mobile web site. It's going to be the

             best site you've ever seen.

            </p>

            <p>

             You can also <a href="#aboutPage">learn more</a> about

             ngocminhtran.com.

            </p>

         </div>
 
         <div data-role="footer">

            <i>Copyright ngocminhtran.com &copy; 2019</i>

         </div>

   </div>

   <div data-role="page" id="aboutPage">

     <div data-role="header">About </div>

        <div data-role="content">

          <p>

            This website is created by ngocminhtran.com. Click

            <a href="#homePage">return</a> to the home page.

          </p>

     </div>

     <div data-role="footer">

        <i>Copyright ngocminhtran.com &copy; 2019</i>

     </div>

  </div>
 
</body>

</html>

Để nhìn thấy sự khác biệt, đoạn mã trên chúng ta chưa dùng thư viện jQuery Mobile. Lưu tập tin và thực thi trên trình duyệt (ví dụ Chrome), kết quả:

Bây giờ chúng ta thêm đoạn mã sử dụng thư viện jQuery Mobile đến <head>, xem lại kết quả:

Lúc này, jQuery Mobile sẽ dựa vào thuộc tính data-role =”page” để xác định các trang và dựa vào id để xác định từng trang cụ thể, ví dụ homePage hay aboutPage. jQuery chỉ hiển thị trang đầu tiên nó bắt gặp (trong ví dụ là homePage) và ẩn các trang khác.


<body>
<div data-role="page" id="homePage">

...

<div data-role="page" id="aboutPage">

...

</body>

Trong ví dụ trên, nhấn dòng liên kết learn more sẽ chuyển đến trang aboutPage:

Nhấn return để trở lại homePage. Sử dụng trong CodePen:

Các phần liên quan đến jQuery Mobile: