简体   繁体   English

从XML元素属性值创建Javascript动态HREF

[英]Javascript Dynamic HREF Creation from XML Element Attribute Values

I want to use javascript to create dynamic HTML links from the attributes of an xml file. 我想使用javascript从xml文件的属性创建动态HTML链接。

I have used the following code to successfully write a list of all of the xml element atrributes (file names) I need to an HTML page, but now need to create links instead. 我使用以下代码成功地将我需要的所有xml元素属性(文件名)的列表写到HTML页面,但是现在需要创建链接。

The anchor text of the links should be the XML element attributes (file names) that I had previously used document.write to write to my HTML page. 链接的锚文本应为我以前使用document.write写入HTML页面的XML元素属性(文件名)。 An example of one of these file names from the xml file would be MyDocument.pdf xml文件中这些文件名之一的示例是MyDocument.pdf。

The href link should be made up of a text string prefix "file:///sdcard/portal/" then append the same xml element attributes (file names) to the end which makes up the link. href链接应由文本字符串前缀“ file:/// sdcard / portal /”组成,然后将相同的xml元素属性(文件名)附加到组成链接的末尾。 An example of this would be file:///sdcard/portal/MyDocument.pdf 例如:file:///sdcard/portal/MyDocument.pdf

I've tried using the document.write method of creating a link but as I also need to use the (x[i].getAttributeNode("name").nodeValue) in the loop to return all of the attributes I'm struggling to make it work. 我尝试使用创建链接的document.write方法,但是由于我还需要在循环中使用[x [i] .getAttributeNode(“ name”)。nodeValue)以返回我正在苦苦挣扎的所有属性使它工作。

Thanks 谢谢

<!DOCTYPE html>
<html>
<head>
<script src="myxml-loadxmldoc.js"> 
</script>

</head>
<body>

<script>
xmlDoc=loadXMLDoc("MyDocuments.xml");
x=xmlDoc.getElementsByTagName("file");

for (i=0;i<x.length;i++)
{

document.write(x[i].getAttributeNode("name").nodeValue);
document.write("<br>");

}

</script>

</body>
</html>

Try this, starting from right above the for loop. for循环的右上方开始尝试此操作。

var path = "file:///sdcard/portal/"; //this will be constant between all iterations
for (i=0;i<x.length;i++)
{
    var filename = x[i].getAttributeNode("name").nodeValue; //the nodefile is the filename
    document.write("<a href=" + path + filename + ">" + filename + "</a>");
    document.write("<br>");

}

That should end up giving you a tag that looks like this in your html: 最终应该为您提供一个在html中看起来像这样的标签:

<a href="file:///sdcard/portal/MyDocument.pdf">MyDocument.pdf</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM