2016-11-11 77 views
3

這可能聽起來很愚蠢,但有沒有一種方法可以製作包含其他標籤的自定義HTML標籤?有沒有辦法制作一個包含其他標籤的自定義HTML標籤?

就像現在我有這樣的事情:

<div> 
    <img></img> 
    <p></p> 
</div> 

有沒有把所有這一切到一個自定義標籤是比較簡單的,看起來像這樣的方式:

<caption-image pic_src="/path" p_text="blahblahblah" /> 

也許使用像XML,如果JavaScript不能做到這一點。

我喜歡這樣的事情的原因是我需要做大量的這些,它可以簡化html並使其更容易更改。

+1

您可能需要一個簡單的循環。 – undefined

+3

這裏有一篇關於使用Javascript創建自定義HTML元素的文章:https://www.html5rocks.com/en/tutorials/webcomponents/customelements/ –

+0

@PeterCollingridge ++!正當我想我已經看到了所有新的網絡技術在河流上漂浮時,一艘巨大的善良的貨船漂浮而過。 – Brad

回答

1

你可以使用框架來做到這一點,如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做同樣的,imgp

相關問題