簡體   English   中英

我如何導入帶有 JavaScript 的 xml 標簽以在 html 中顯示圖像

[英]How do i import a xml tag with JavaScript to display an image in html

我對 XML 非常陌生。我需要使用 JavaScript 導入 XML 圖像以顯示在我的 HTML 文件中。 我需要在我的 xml 中創建一個名為“圖像”的標簽,標簽應該顯示一個圖像路徑,該路徑將在我的 html 頁面中顯示圖像。 我有多張圖片,但每個問題一張。 我的 XML 在下面。

<questionText>
    <question>Question</question>
        <image>images/image_path1.png</image>
        <answers>
            <choice correct="0">answer1</choice>
            <choice correct="0">answer2</choice>
            <choice correct="1">answer3</choice>
            <choice correct="0">answer4</choice>
    </answers>
</questionText>
<questionText>
    <question>Question</question>
        <image>images/image_path2.png</image>
        <answers>
            <choice correct="0">answer1</choice>
            <choice correct="1">answer2</choice>
            <choice correct="0">answer3</choice>
            <choice correct="0">answer4</choice>
    </answers>
</questionText>

可以使用DomParser中的DomParser解析XML,然后使用document.createElement動態創建圖片。

 var xml = ` <questions> <questionText> <question>Question</question> <image>images/image_path1.png</image> <answers> <choice correct="0">answer1</choice> <choice correct="0">answer2</choice> <choice correct="1">answer3</choice> <choice correct="0">answer4</choice> </answers> </questionText> <questionText> <question>Question</question> <image>images/image_path2.png</image> <answers> <choice correct="0">answer1</choice> <choice correct="1">answer2</choice> <choice correct="0">answer3</choice> <choice correct="0">answer4</choice> </answers> </questionText></questions>`; parser = new DOMParser(); xmlDoc = parser.parseFromString(xml, "text/xml"); const images = xmlDoc.getElementsByTagName("image"); for (let image in images){ if (images[image].tagName == "image"){ let imagePath = images[image].innerHTML; createImage(imagePath); } } function createImage(path){ var img = document.createElement("img"); img.src = path; document.body.appendChild(img); }

參考資料:點這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM