简体   繁体   English

使用javascript通过div中的链接循环

[英]Looping through links in div with javascript

I have a hta app that parses some xml using xslt and populates a div within the hta page with the result. 我有一个hta应用程序使用xslt解析一些xml并在hta页面中填充结果的div。 The result contains a table that has a summary of the xml with hyperlinks on the counts of xml elements - example below 结果包含一个表,其中包含xml的摘要以及xml元素计数的超链接 - 如下所示

There will be a button on the page, outside the "content" div that will allow the user to save the page to a static html file without the hyperlinks. 在“content”div之外的页面上将有一个按钮,允许用户将页面保存到没有超链接的静态html文件。 I have the following javascript below, but when clicking the "Save" button the hyperlink is only removed from the first item, not the second..(there will be many more actual hyperlinks in the proper version). 我在下面有以下javascript,但是当点击“保存”按钮时,超链接仅从第一个项目中移除,而不是第二个项目..(在正确的版本中将会有更多的实际超链接)。 What am I doing wrong - I assume it is something to do with the loop....and must be done in javascript, no jquery etc - long story as to why... 我做错了什么 - 我认为它与循环有关....并且必须在javascript中完成,没有jquery等 - 长篇故事为什么......

function SaveContent() {
    var myContent = document.getElementById("content")
    var myLinks = myContent.getElementsByTagName('a')

    for (var myItem = 0; myItem < myLinks.length; myItem++) {
        var myChild = myLinks[myItem]
        var myParent = myChild.parentNode
        var myValue = myChild.innerText
        myChild.parentNode.removeChild(myChild)
        myParent.innerText = myValue
        /*code to save to file will go here */
    }
}

<div id="content">
    <table>
        <tr>
            <td>Status</td>
            <td>Count</td>
        </tr>
        <tr>
            <td>New</td>
            <td>
                <a href="#">34</a>
            </td>
        </tr>
        <tr>
            <td>Closed</td>
            <td>
                <a href="#">78</a>
            </td>
        </tr>
    </table>
</div>

Many thanks 非常感谢

getElementsByTagName is a live list. getElementsByTagName是一个实时列表。 When you call removeChild on an item, it is removed from the list... but the index of your loop continues on! 当您在项目上调用removeChild时,它将从列表中删除...但循环的索引仍在继续!

A typical solution is: 典型的解决方案是:

for( var myItem = myLinks.length-1; myItem >= 0; myItem--)

ie. 即。 working from the end to the beginning. 从最后到开始工作。 This is also good if your code might add more links, as they will not be iterated. 如果您的代码可能添加更多链接,这也很好,因为它们不会被迭代。

Try this: 尝试这个:

    function SaveContent() {
        var myContent = document.getElementById("content")
        var myLinks = myContent.getElementsByTagName('a')

        while (myLinks.length) {
            var child = myLinks[0];
            var parent = child.parentNode;
            var value = child.innerText;
            parent.removeChild(child);
            parent.innerText = value;               
        }
    }

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

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