将.txt文件读入HTML图像映射

时间:2016-07-25 02:10:27

标签: javascript html

我是HTML的初学者,正在编写一个网页,其中画布被分割成网格。用户可以将鼠标悬停在网格内的矩形上并突出显示它们。

我有很多矩形坐标存储在.txt文件中(每行有4个坐标用空格分隔),我希望逐行读入文件并将其作为变量输入到我的代码中,就像我可能用Python一样。

<area shape="rect" coords="xmin,xmax,ymin,ymax" href="#"...>

任何建议/指向我的地方都非常感谢,因为我手动输入的坐标太多了!

1 个答案:

答案 0 :(得分:0)

您正在寻找的是AJAX。您可以使用以下内容。

var xhr = new XMLHttpRequest();
xhr.open("GET", "coords.txt", true);

xhr.onload = function(e) {
    if(this.status == 200) {
        // get text contents
        var coords = this.responseText.split("\n");
        coords.forEach(function(coord) {
            // create new area element
            var area = document.createElement("area");
            area.shape = "rect";
            area.coords = coord.replace(/ /g,",");    // replace spaces with commas
            area.href = "#";

            // get your map element somehow
            document.getElementById("myMap").appendChild(area);
        });
    }
};

xhr.send();
相关问题