[英]Make repetitive HTML with non-repetitive values
我有这个代码
<tr>
<td>
<img
src="/divide.png"
alt="?"
width="20px"
/>
</td>
<td>Divide</td>
<td>1</td>
<td>a24</td>
</tr>
<tr>
<td>
<img
src="/multiply.png"
alt="?"
width="25px"
/>
</td>
<td>Exponen</td>
<td>1</td>
<td>a25</td>
</tr>
它们非常重复 HTML。 这些只是重复的事情中的两个,还有数百个。
非常糟糕的服务器对此有点摇摆不定,所以我在想有没有办法压缩它?
像这样的东西:
<td v1="/divide.png" v2="Divide" v3="1" v4="a24">
它会返回与
<tr>
<td>
<img
src="/divide.png"
alt="?"
width="20px"
/>
</td>
<td>Divide</td>
<td>1</td>
<td>a24</td>
</tr>
可能吗? 如果是,我该怎么做? 任何编程语言,javascript,PHP? 我认为 javascript 循环可能是可能的,但我不知道该怎么做。
你可以用两种方法来做
var comWrap = document.querySelector('#wrapper table tbody') var data = [ [ '/image.png', 'this is an image', 'Devide', 1, 'a16', ], [ '/image2.png', 'this is image2', 'Devide2', 2, 'a17', ], [ '/image3.png', 'this is image3', 'Devide3', 3, 'a316', ], [ '/image4png', 'this is image4', 'Devide5', 4, 'a163', ], [ '/image6png', 'this is image6', 'Devide5', 5, 'a15', ], [ '/image6png', 'this is an image', 'Devide', 6, 'a16', ] ] for(let i = 0; i < data.length;i++){ insertRow(data[i]) } function insertRow(arr){ let [src, alt, name, number, info] = arr; // <--- sorting is very important let com = ` <tr> <td> <img src="${src}" alt="${alt}" width="20px" /> </td> <td>${name}</td> <td>${number}</td> <td>${info}</td> </tr>` //<--- it's very important to add `` and not '' comWrap.insertAdjacentHTML('beforeend', com) } /* or you can directly loop it for (let i = 0; i < data.length;i++){ let [src, alt, name, number, info] =data[i]; let com = ` <tr> <td> <img src="${src}" alt="${alt}" width="20px" /> </td> <td>${name}</td> <td>${number}</td> <td>${info}</td> </tr>` //<--- it's very important to add `` and not '' comWrap.insertAdjacentHTML('beforeend', com) } */
/*not important*/ table { width: 100%; height: 100vh; }
<div id="wrapper"> <table> <tbody> </tbody> </table> </div>
class CustomRow extends HTMLElement { // (1) connectedCallback() { this.innerHTML = ` <tr> <td> <img src="${this.getAttribute('src')}" alt="${this.getAttribute('alt')}" width="${this.getAttribute('width')}" /> </td> <td>${this.getAttribute('name')}</td> <td>${this.getAttribute('num')}</td> <td>${this.getAttribute('info')}</td> </tr>` } } customElements.define("custom-row", CustomRow); // (2)
/*you can also select it in query selectors*/ custom-row{ background: red; padding: 20px; }
<custom-row src="/divide.png" alt="this is alt" width="20px" name="Divide" num="1" info="a16"></custom-row>
https://caniuse.com/custom-elementsv1
https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define#browser_compatibility
也许你猜的意思是“组件”。它使用一个目标和属性来描述许多 html 标签。好吧,你可以通过像 vue、react 和源组件这样的 js 框架或像 php 智能模板引擎这样的服务器语言模板引擎来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.