最近在学习前端的相关内容,在写一个商城页面的时候除了商品图片,链接不同外,其余的代码几乎一致(代码如下),怎么才能像Java封装方法那样提取出相同部分,简化代码,请兄弟们指教一下!
<div class="products">
<div class="image_1">
<a href="#" class="p_link">
<img src="../image/bookimage/IT之火.jpg" >
</a>
</div>
<div class="info_1">
<a href="#" class="p_link">
<font style="color: black;">IT之火:计算机技术与社会</font><br>
</a>
<font style="color: darkred;">惊喜价:¥85.70</font><br>
<font style="color: gray; font-size: calc(14px);">市场价:¥
<font style="text-decoration: line-through;">99.00</font>
</font>
</div>
</div>
<div class="products">
<div class="image_1">
<a href="#" class="p_link">
<img src="../image/bookimage/失明症漫记.jpg" >
</a>
</div>
<div class="info_1">
<a href="#" class="p_link">
<font style="color: black;">萨拉马戈:失明症漫记</font><br>
</a>
<font style="color: darkred;">惊喜价:¥59.00</font><br>
<font style="color: gray; font-size: calc(14px);">市场价:¥
<font style="text-decoration: line-through;">59.00</font>
</font>
</div>
</div>
可以做成一个js文件,用document.write输出,在需要的地方用script加载这个js文件,示例如下,有帮助麻烦点个采纳【本回答右上角】,谢谢~~有其他问题可以继续交流~
pro.js
document.write(`<div class="products">
<div class="image_1">
<a href="#" class="p_link">
<img src="../image/bookimage/IT之火.jpg" >
</a>
</div>
<div class="info_1">
<a href="#" class="p_link">
<font style="color: black;">IT之火:计算机技术与社会</font><br>
</a>
<font style="color: darkred;">惊喜价:¥85.70</font><br>
<font style="color: gray; font-size: calc(14px);">市场价:¥
<font style="text-decoration: line-through;">99.00</font>
</font>
</div>
</div>
<div class="products">
<div class="image_1">
<a href="#" class="p_link">
<img src="../image/bookimage/失明症漫记.jpg" >
</a>
</div>
<div class="info_1">
<a href="#" class="p_link">
<font style="color: black;">萨拉马戈:失明症漫记</font><br>
</a>
<font style="color: darkred;">惊喜价:¥59.00</font><br>
<font style="color: gray; font-size: calc(14px);">市场价:¥
<font style="text-decoration: line-through;">59.00</font>
</font>
</div>
</div>`)
在需要的地方用script导入
其他html代码.....
<!--注意修改pro.js为相对于当前html页面的相对路径,如果发布后通过http测试,可以用绝对路径,从网站根目录开始计算,如“/comm/pro.js”-->
<script src="pro.js"></script>
其他html代码.....
可以引入vue部分功能,用组件
可以考虑下webComponent,用原生组件实现
框架中可以用组件 。原生js中或者jq可以,封装一个函数 或者iframe (这个适用于,什么都没改变)
你现在才学到css,学到后面就可以将代码优化了;现目前阶段,想实现代码优化,就是少用行内样式。
如果是初学者,可以考虑使用JQ用$对象.html()输出重复代码
如果是基础比较扎实的,可以考虑使用vue.js,通过for循环实现重复代码
如果符合你的需求,不清楚的地方可以咨询我
初学也可以尝试下jstl标签库的<c:foreach>标签,循环输出,列如这种