javascript - 无法弄清楚我在 JavaScript 中的 if 语句有什么问题 [9 月 1 日更新 看来我的 for 循环运行了两次,我该如何解决?]

标签 javascript html for-loop

var MarkUpChecker = (function iffe() {
    'use strict';
    var URLS = {
            'foo': 'http://foo.com',
            'bar': 'http://bar.com',
            'baz': 'http://baz.com',
            'yay': 'http://www.yay.com',
            'blargh': 'http://www.blargh.com'
        },

        publicAPI;

    function getURL() {
        for (var i = 0; i < arguments.length; i++) {
            return URLS[arguments[i]];
        }
    }

    publicAPI = {

        addURL: function() {
            for (var i = 0; i < arguments.length; i += 2) {
                URLS[arguments[i]] = arguments[i + 1];
            }
            console.dir(URLS);
            return URLS;
        },
        addTag: function() {
            var doc = document,
                internal_h1 = doc.querySelectorAll('.internal_h1'),
                sheet = doc.createElement('style');
            for (var i = 0; i < internal_h1.length; i++) {
                internal_h1[i].innerHTML = '<h1>' + internal_h1[i].innerHTML + '</h1>';
                sheet.innerHTML = 'h1 {font-family: Helvetica, Arial, sans-serif !important; font-weight: 200!important; font-size: 22px !important; color: #333; margin: 3px 0px 6px; line-height: 24px !important;};'
                doc.body.appendChild(sheet);
            }
        },

        searchDoc: function() {
            function insertAfter(newNode, referenceNode) {
                referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
            }

            var link, url, parser, newPathName = '',
                emailUrl = /img\//gi,
                tsUrl = /\/REPSuite\/static\/html\/inews_archives\/img\//gi,
                newstr = '',
                doc = document,
                container,
                container_id,
                container_links,
                container_images,
                documentTableWrapper,
                docBodyFirstChild,
                nodeToTargetToInsertLP;

            if (!doc.getElementById('container')) {
                container = doc.createElement('div');
                container.setAttribute('id', 'container');
                container.className = 'container-avon-representative-news';
                container_links = container.getElementsByTagName('a');
                container_id = doc.getElementById('container');
                docBodyFirstChild = doc.body.firstChild;
                nodeToTargetToInsertLP = doc.getElementsByClassName('flexTile')[4];


                if (nodeToTargetToInsertLP) {
                    documentTableWrapper = doc.getElementsByClassName('marginfix')[0];
                    container.appendChild(documentTableWrapper);
                    insertAfter(container, nodeToTargetToInsertLP);
                } else {
                    documentTableWrapper = doc.getElementsByTagName('table')[0];
                    container.appendChild(documentTableWrapper);
                    doc.body.insertBefore(container, docBodyFirstChild);
                }


            } else {
                container_links = doc.getElementById('container').getElementsByTagName('a');
            }
            container_images = container.getElementsByTagName('img');
            for (var i = 0; i < container_images.length; i++) {
                if (arguments[0] == "foo" || arguments[1] == "bar") {
                    container_images[i].src = container_images[i].src.replace(emailUrl, '/images/news/');
                } else {
                    container_images[i].src = container_images[i].src.replace(emailUrl, '/static/images/alt_news/');

                }
            }

            for (var i = 0, len = arguments.length; i < len; i++) {
                url = getURL(arguments[i]);
                for (var j = 0, jlen = container_links.length; j < jlen; j++) {
                    link = container_links[j];

                    if (link.href.indexOf(url) != -1) {
                        parser = document.createElement('a');
                        parser.href = link.href;

                        link.setAttribute('target', '_self');
                        newPathName = parser.pathname;


                        if (newPathName.search(/Executive|District|Division|National/) != -1) {
                            newPathName = newPathName.split('/').pop();
                            newstr = newPathName;
                            link.href = newstr;

                        }
                    } else {
                        link.setAttribute('target', '_blank');
                    }
                }

            }
        }
    };
    return publicAPI;
})();

我的问题是我的条件似乎没有根据我认为应该的条件将目标 _self 属性添加到 href

这是一个函数的摘录,可以在上面的代码片段中找到。

        for (var i = 0, len = arguments.length; i < len; i++) {
            url = getURL(arguments[i]);
            for (var j = 0, jlen = container_links.length; j < jlen; j++) {
                link = container_links[j];

                if (link.href.indexOf(url) != -1) { //problem seems to be here
                    parser = document.createElement('a');
                    parser.href = link.href;

                    link.setAttribute('target', '_self');
                    newPathName = parser.pathname;


                    if (newPathName.search(/Executive|District|Division|National/) != -1) {
                        newPathName = newPathName.split('/').pop();
                        newstr = newPathName;
                        link.href = newstr;

                    }
                } else {
                    link.setAttribute('target', '_blank');
                }
            }

        }

为了给您一些背景知识,该脚本的主要功能是自动执行我必须每周对新闻通讯执行的冗余任务,该新闻通讯重新用于静态网页/登录页面:

HTML:

<a href="http://foo.com/path/to_page.aspx"> 
    <img src="img/some_image.jpg">
</a>

脚本遍历 DOM,查找符合条件的 URLS 并去除基本 URL、一些路径名并将目标 _self 应用于 href

它还会更改我的图像的路径名!

在 HTML 中,我调用这个接受字符串的函数:

    MarkUpChecker.searchURL('foo', 'bar');

该字符串表示我想要定位并应用更改的 URL:

    var URLS = {
        'foo': 'http://foo.com',
        'bar': 'http://bar.com',
        'baz': 'http://baz.com',
        'yay': 'http://www.yay.com',
        'blargh': 'http://www.blargh.com'
    },

此函数用于循环对象:

    function getURL() {
        for (var i = 0; i < arguments.length; i++) {
            return URLS[arguments[i]];
        }
    }

最后是 searchURL 函数:

 searchDoc: function() {
            function insertAfter(newNode, referenceNode) {
                referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
            }

            var link, url, parser, newPathName = '',
                emailUrl = /img\//gi,
                tsUrl = /\/REPSuite\/static\/html\/inews_archives\/img\//gi,
                newstr = '',
                doc = document,
                container,
                container_id,
                container_links,
                container_images,
                documentTableWrapper,
                docBodyFirstChild,
                nodeToTargetToInsertLP;

            if (!doc.getElementById('container')) {
                container = doc.createElement('div');
                container.setAttribute('id', 'container');
                container.className = 'container-avon-representative-news';
                container_links = container.getElementsByTagName('a');
                container_id = doc.getElementById('container');
                docBodyFirstChild = doc.body.firstChild;
                nodeToTargetToInsertLP = doc.getElementsByClassName('flexTile')[4];


                if (nodeToTargetToInsertLP) {
                    documentTableWrapper = doc.getElementsByClassName('marginfix')[0];
                    container.appendChild(documentTableWrapper);
                    insertAfter(container, nodeToTargetToInsertLP);
                } else {
                    documentTableWrapper = doc.getElementsByTagName('table')[0];
                    container.appendChild(documentTableWrapper);
                    doc.body.insertBefore(container, docBodyFirstChild);
                }


            } else {
                container_links = doc.getElementById('container').getElementsByTagName('a');
            }
            container_images = container.getElementsByTagName('img');
            for (var i = 0; i < container_images.length; i++) {
                if (arguments[0] == "foo" || arguments[1] == "bar") {
                    container_images[i].src = container_images[i].src.replace(emailUrl, '/images/news/');
                } else {
                    container_images[i].src = container_images[i].src.replace(emailUrl, '/static/images/alt_news/');

                }
            }

            for (var i = 0, len = arguments.length; i < len; i++) {
                url = getURL(arguments[i]);
                for (var j = 0, jlen = container_links.length; j < jlen; j++) {
                    link = container_links[j];

                    if (link.href.indexOf(url) != -1) {
                        parser = document.createElement('a');
                        parser.href = link.href;

                        link.setAttribute('target', '_self');
                        newPathName = parser.pathname;


                        if (newPathName.search(/Executive|District|Division|National/) != -1) {
                            newPathName = newPathName.split('/').pop();
                            newstr = newPathName;
                            link.href = newstr;

                        }
                    } else {
                        link.setAttribute('target', '_blank');
                    }
                }

            }
        }

我通过调试器观察到的是,当它确实去除它应用目标 _blank 到所有 hrefs 的路径名时p>

另外——有趣的是脚本在另一个上下文/环境中工作,不需要通过这部分代码:

 if (newPathName.search(/Executive|District|Division|National/) != -1) {
    newPathName = newPathName.split('/').pop();
    newstr = newPathName;
    link.href = newstr;

}

在那种情况下它工作得很好。

提前致谢!

2016 年 8 月 29 日更新

有人提到这个来试试这个:

var urls = [];
for (var i = 0, len = arguments.length; i < len; i++) {
    urls[i] = getURL(arguments[i]);
}
for (var j = 0, jlen = container_links.length; j < jlen; j++) {
    link = container_links[j];
    if (urls.every(function(url) {
        return link.href.indexOf(url) !== -1;
    }) {
        // none of the urls matched the link
    } else {
        // at least one of the urls matched the link
    }
}

但我无法将它与我的较大代码集成。任何帮助将不胜感激!

8 月 29 日更新 #2

在另一篇文章中,有人也提到我的一个功能逻辑可能是错误的。不幸的是,此人并没有深入了解细节。

enter image description here

8 月 29 日更新 #3 好的。我想我已经很接近了,我单步执行了我的代码并添加了断点,看起来我的代码循环遍历了所有链接两次

enter image description here enter image description here

屏幕截图显示了如何将 target _self 应用于链接,但由于某种原因,循环再次运行并跳转到 else block ,从而添加 将 _blank 定位到所有链接?

这里又是原始 for 循环的代码!谢谢!

for (var i = 0, len = arguments.length; i < len; i++) {


  url = getURL(arguments[i]);
    for (var j = 0, jlen = container_links.length; j < jlen; j++) {
        link = container_links[j];

        if (link.href.indexOf(url) != -1) { //problem seems to be here
            parser = document.createElement('a');
            parser.href = link.href;

            link.setAttribute('target', '_self');
            newPathName = parser.pathname;


            if (newPathName.search(/Executive|District|Division|National/) != -1) {
                newPathName = newPathName.split('/').pop();
                newstr = newPathName;
                link.href = newstr;

            }
        } else {
            link.setAttribute('target', '_blank');
        }
    }

}

最佳答案

您的代码中存在多个问题,包括逻辑问题。例如

function getURL() {
    for (var i = 0; i < arguments.length; i++) {
        return URLS[arguments[i]];//always returns arguments[0]
    }
}

我以接受和返回数组的方式重写了它(请参阅下面的 jsfiddle)。
下一期

  //root problem. this for loop See solution in JSFiffle
  for (var i = 0, len = arguments.length; i < len; i++) { // Using a for loop to allow unlimited arguments to be passed in
    url = getURL(arguments[i]); // We are calling the publicApi.getURL() method and passing the looped argument from above

    //and rewrite target again and again. I remove outer loop
    for (var j = 0, jlen = avon_rep_container_links.length; j < jlen; j++) { // This loop goes over the whole documents links...
      link = avon_rep_container_links[j];
      if (link.href.indexOf(url) !== -1) { //...and we are checking each argument passed in to see if it matches the object value stored in the getURL function e.g. like a switch statement..
        parser = document.createElement('a'); //...if so we are essentially adding a blank tag to all the documents in the document
        parser.href = link.href;//parser isn't used 

        link.setAttribute('target', '_self');//will be changed in the next loop
        newPathName = parser.pathname;


        if (newPathName.search(/Executive|District|Division|National/) != -1) { // Added check for these strings for SMO page
          newPathName = newPathName.split('/').pop();
          newstr = newPathName;

        } else {
          newstr = newPathName;
        }
        link.href = newstr;
      } else {
        link.setAttribute('target', '_blank');

      }
    }

许多变量已声明但未使用。我没有碰他们。

target 的问题已在更新的 JSFiddle 中修复.

关于javascript - 无法弄清楚我在 JavaScript 中的 if 语句有什么问题 [9 月 1 日更新 看来我的 for 循环运行了两次,我该如何解决?],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38919624/

相关文章:

javascript - 通过电子邮件而不是 ID 搜索

PHP mailto() 表单

java - 在 Java Swing 的 JEditorPane 中添加 HTML

python - 避免 for 循环变量切入 Python 全局命名空间的方法

javascript - Wordpress TinyMCE 去除 OnClick 和 OnChange(需要 jQuery)

javascript - 单击忘记按钮表单应该使用 jquery 进行验证

javascript - CSS 未加载或应用于从服务器加载的页面

python - 避免Python中的冗余循环

for-loop - 使用具有 2 个参数的机器人框架进行循环

javascript - 以给定格式打印数字