这听起来可能很愚蠢,但是有没有办法我可以制作一个包含其他标签的自定义HTML标签呢?
就像现在,我有这样的事情:
<div>
<img></img>
<p></p>
</div>
有没有一种方法可以将所有这些方法放到更简单的自定义标记中,如下所示:
<caption-image pic_src="/path" p_text="blahblahblah" />
如果Javascript无法做到,则可能使用类似XML的格式。
我想要这样的原因是,我需要做很多这样的事情,这将简化html并使更改变得更容易。
您可以使用AngularJS或ReactJS之类的框架来执行此操作。但是我认为您现在很难学习它,因此您可以自己编写一些Javascript。
您可以像创建标签一样创建标签,并使用javascript对其进行解析,从标签中获取所需内容并构建HTML页面。
这将为您做(我假设您正在使用jQuery):
<caption-image pic_src="path1.png" p_text="blahblahblah"></caption-image>
<caption-image pic_src="path2.png" p_text="123123123"></caption-image>
<caption-image pic_src="path3.png" p_text="this is an image"></caption-image>
<caption-image pic_src="path4.png" p_text="just some text"></caption-image>
<div id="someContainer">
<figure id="figTemplate">
<img src="" alt="">
<figcaption></figcaption>
</figure>
</div>
<script>
$.each($('caption-image'), function (key, obj) {
var src = $(obj).attr('pic_src');
var p_text = $(obj).attr('p_text');
$(obj).hide(); //or remove if you want $(obj).remove()
var clone = $('#figTemplate').clone();
clone.removeAttr('id')
.children('img').attr('src', src).attr('alt', p_text).end()
.children('figcaption').text(p_text);
$('#someContainer').append(clone);
});
</script>
我使用的figure
元素,因为它不正是你想要什么,而是你可以做到使用相同的div
,img
并p
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句