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

时间:2016-08-12 13:49:21

标签: 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;
})();
&#13;
&#13;
&#13;

我的问题是我的条件似乎没有根据我认为应该的条件将目标_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,查找符合条件的URL并删除基本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

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

 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块,因此添加了target _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');
        }
    }

}

2 个答案:

答案 0 :(得分:1)

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

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');

      }
    }

声明但未使用的变量很多。我没碰过它们。

更新后的JSFiddle修复了target的问题。

答案 1 :(得分:0)

<强>被修改!

为您的主播<a>添加ID并尝试使用jQuery更改<a>代码target属性:

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

和jQuery代码来修改属性:

if (link.href.indexOf(url) !== -1) {
    $('#custom_target').attr('target', '_self');
}
else{
    $('#custom_target').attr('target', '_blank');
}