最近在學習 JS 的面向對象實現,看「Javascript 設計模式」看不明白 JS 關於接口是怎麼實現的。css
下面有一段在JS中使用接口的代碼,不知道是否是你在《JavaScript設計模式》中看到的,該段代碼模擬了接口,支持多個接口的狀況。html
<script> var url = "http://192.168.1.103:8000/data.json"; var xianli = document.getElementById("xianli"); var mingyang=document.getElementsByClassName("mingyang") fetch(url) .then((response) => { return response.text(); }) .then((data)=>{ var liujie = JSON.parse(data); var html='' for(var i=0;i<liujie.length;i++){ var zeyu="<li><div class='box'><div class='tu'><a href='#'><img src="+liujie[i].img+"></a><span>"+liujie[i].tu+"</span></div><div class='yu'><h2><a href='#'>"+liujie[i].shuju+"</a></h2><p>"+liujie[i].jushi+"    "+liujie[i].duoda+"</p><p class='add'><a href='#' >"+liujie[i].dizhi1+"</a> <a href='#'>"+liujie[i].dizhi2+"</a><em></em>"+liujie[i].dizhi3+"</p><div class='jjr'>來自經紀人: <span>"+liujie[i].ren1+"</span><span>"+liujie[i].ren2+"</span></div><div class='money'><b>"+liujie[i].rem+"</b>"+liujie[i].fen+"</div></div></div></li>"; html=html+zeyu; } xianli.innerHTML=html }) </script>
[ {"img":"1.jpg","tu":"11圖","shuju":"整租|義,和,莊東里 精裝兩居室 家電齊全地鐵沿線 出行購","jushi":"2室1廳1衛","duoda":"86㎡","dizhi1":"黃村","dizhi2":"義和莊東里...","dizhi3":"距離4號線黃村火車站地鐵站792米","ren1":"安易居房地產 - 安易居房地產總店","ren2":"劉興棟 ","rem":"3500","fen":"元/月"}, ]
html文本只需寫一點就能夠,由於都帶入了js裏了json
<body> <div class="mi"> <ul class="mingyang" id="xianli"></ul> </div> </body>
<style> a { text-decoration: none; } body { margin: 0; padding: 0; } .box { width: 994px; height: 171px; border: 1px solid #ccc; margin: 100px; position: relative; } .tu { width: 147px; height: 170px; float: left; } .tu img { width: 147px; height: 110px; padding-top: 30px; } .tu span { display: inline-block; width: 40px; border: 1px solid #ccc; font-size: 14px; text-align: center; background: #333; position: absolute; opacity: .5; top: 30px; left: 0; color: #fff; } .yu { width: 670px; height: 140px; float: left; } .yu h2 a { color: #333; padding-left: 20px; } p { font-size: 10px; color: #333; padding-left: 20px; } p a { color: #333; } span { font-size: 10px; color: #333; } .jjr { font-size: 10px; color: #333; padding-left: 20px; } .money{ display: inline-block; position: absolute; top:20px; right: 20px; color:#f00 } .money b{ font-size:32px; } </style>
[ {"img":"1.jpg","tu":"11圖","shuju":"整租|義,和,莊東里 精裝兩居室 家電齊全地鐵沿線 出行購","jushi":"2室1廳1衛","duoda":"86㎡","dizhi1":"黃村","dizhi2":"義和莊東里...","dizhi3":"距離4號線黃村火車站地鐵站792米","ren1":"安易居房地產 - 安易居房地產總店","ren2":"劉興棟 ","rem":"3500","fen":"元/月"}, {"img":"1.jpg","tu":"11圖","shuju":"整租|義,和,莊東里 精裝兩居室 家電齊全地鐵沿線 出行購","jushi":"2室1廳1衛","duoda":"86㎡","dizhi1":"黃村","dizhi2":"義和莊東里...","dizhi3":"距離4號線黃村火車站地鐵站792米","ren1":"安易居房地產 - 安易居房地產總店","ren2":"劉興棟 ","rem":"3500","fen":"元/月"} ]