JS State Pattern

本文介绍了一种使用状态模式管理页面的方法,通过定义Pagestate类来切换不同的页面状态,如首页、关于我们和联系我们。每个状态都有相应的DOM操作以更新页面内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每个page作为一个state

定义pagestate类

const Pagestate =function(){
  let currentState = new homeState(this);

  this.init = function(){
    this.change(new homeState);
  }

  this.change= function(state){
    currentState = state;
  }
};

home state

//Home state
const homeState = function(page){
  document.querySelector('#heading').textContent = null;
  document.querySelector('#content').innerHTML=`
    <div class="jumbotron">
    <h1 class="display-4">Hello, world!</h1>
    <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
    <hr class="my-4">
    <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
    <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
    </div>
  `;
};

about state

//About state
const aboutState = function(page){
  document.querySelector('#heading').textContent ='About Us';
  document.querySelector('#content').innerHTML=`
    <p>This is the about page</p>
`;
};

contact state

//Contact state
const contactState = function(page){
  document.querySelector('#heading').textContent ='Contact Us';
  document.querySelector('#content').innerHTML=`
    <form>
    <div class="form-group row">
      <label for="staticEmail" class="col-sm-2 col-form-label">Email</label>
      <div class="col-sm-10">
        <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="email@example.com">
      </div>
    </div>
    <div class="form-group row">
      <label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
      <div class="col-sm-10">
        <input type="password" class="form-control" id="inputPassword">
      </div>
    </div>
  </form>
`;
};

初始化page

//Instantiate pageState
const page= new Pagestate();

//Init the first state
page.init();

定义三个button

//UI Vars
const home = document.getElementById('home'),
      about = document.getElementById('about'),
      contact = document.getElementById('contact');

//Home
home.addEventListener('click',function(e){
  page.change(new homeState);
  e.preventDefault();
});

//About
about.addEventListener('click',function(e){
  page.change(new aboutState);
  e.preventDefault();
});

//Contact
contact.addEventListener('click',function(e){
  page.change(new contactState);
  e.preventDefault();
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值