2つのページを達成するためのlocalStorage通信、原則カートショッピング。

以下のような:A、Bページ、Aのための製品ページ、ショッピングカートページへのB、2つのページを同時に開いて、自分のカートにページをクリック項目を追加、カートのページのBスイッチがどのように製品の情報を表示します

  1. localStroage、ページストアデータlocalStroageを使用して、BはのlocalStorageでページデータを読み込み、
  2. キーポイント:のlocalStorageにデータを保存するとき、どのようにページBのページ知ります
  3. localStorage「ストレージ」イベントがあります
  4. window.addEventListener(「保存」、コールバック)、ページ保存されたデータ、Bページモニタもの

 

页面
<ボタンのid = "追加">添加一件商品到购物车</ button>の
  <ボタンID = "デル">删除一件商品从购物车</ボタン> 
ます。<script type = "text / javascriptの"> 
    window.onload =関数(){ 
      のdocument.getElementById( '追加')のonclick =関数(){ 
        数(真)
      } 

      のdocument.getElementById( 'デル')のonclick =関数(){ 
        数(偽)
      } 

      関数count (フラグ){ 
        カウント= localStorage.getItem( 'カウント')とするJSON.parse(localStorage.getItem() 'カウント')カウント:0;?。
        IF(フラグ){ 
          カウント+ = 1; 
        }他{ 
          (!数)であればリターン。
          数- = 1;
          カウント
        } 
        localStorage.setItem( 'カウント'、JSON.stringify(countObj))
      } 
    } 

B页面
<DIV CLASS = "カート"> 
  购物车产品数量:
  <スパンクラス= "カウント"> 0 </スパン> 
</ div> 
ます。<script type = "text / javascriptの"> 
      'カウント')。document.querySelectorのTextContent = localStorage.getItem('数')JSON.parse(localStorage.getItem('数'))カウント:?。0; 
      window.addEventListener( 'ストレージ'、関数(イベント){ 
        にconsole.log(JSON.parse(event.newValue).count)
        。document.querySelector( 'カウント')のTextContent = JSON.parse(event.newValue)。数
      })
</スクリプト>

  

おすすめ

転載: www.cnblogs.com/7Ezreal/p/11984380.html