需要Javascript或JQuery中的花式循环

时间:2021-11-13 21:20:10

This is my first post here, although I have used this site for many years to help me find snippets of code to achieve the results I needed. So, if I haven't posted this correctly, forgive me in advance...

这是我在这里的第一篇文章,虽然我已经使用这个网站多年来帮助我找到代码片段来实现我需要的结果。所以,如果我没有正确发布,请提前原谅我...

I have an iframe on my page that loads the first of a set of images from ancestry.com:

我的页面上有一个iframe,它从ancestry.com加载了一组图像中的第一个:

    <div id="ancestryiframeholder">
    <div class="well padding larger" align="center">Some Districts, like in cities and towns have more than one Sub-district included in the table. The program only automatically loads the first Sub-district from the set.<br />You will have to use Ancestry's menu below this message to choose the subsequent Sub-district(s). See the Sub-district list for more information.
    <iframe id="iframe" class="" src="http://interactive.ancestry.com/8991/1921_041-E002904764/8517860#?imageId=1921_043-e002907748" style="height:300px; width:100%;"></iframe>
    </div>
    </div>

I also have a group of links in a list that varies in length from one page to the other, based upon the place names for that particular page.

我还有一组列表中的链接,根据该特定页面的地名,从一个页面到另一个页面的长度不同。

    <ul><br /><br />
    <li><a id="fergusonscove" href="/census/novascotia/test/fergusonscove.html" rel="#iframe">Ferguson's Cove</a></li>
    <li><a id="herringcove" href="/census/novascotia/test/herringcove.html" rel="#iframe">Herring Cove</a></li>
    <li><a id="portugeusecove" href="/census/novascotia/test/portugeusecove.html" rel="#iframe">Portugeuse Cove</a></li>
    </ul>

This list can be long, depending on how many places there are. When user clicks one of these links, two things happen. A document from my server is loaded into a div with the rel iframe. And, a new image from Ancestry is loaded into the previous iframe I mentioned above with the id iframe. I am making this happen by using the script from here - http://www.dynamicdrive.com/dynamicindex17/ajaxtabscontent/index.htm - to accomplish the loading of the document into the iframe. I am then using the code below to load the new image from Ancestry into the other iframe. All works as expected. The new image loads into the iframe without the need for a page refresh.

此列表可能很长,具体取决于有多少个地方。当用户单击其中一个链接时,会发生两件事。我的服务器中的文档被加载到具有rel iframe的div中。并且,来自Ancestry的新图像被加载到我上面提到的id iframe的上一个iframe中。我通过使用此处的脚本 - http://www.dynamicdrive.com/dynamicindex17/ajaxtabscontent/index.htm - 来完成将文档加载到iframe中。然后我使用下面的代码将Ancestry中的新图像加载到另一个iframe中。一切正常。新图像加载到iframe而无需页面刷新。

    <script>
    $(document).ready(function () {
    var addEvent = (function(){return window.addEventListener? function(el, ev, f){
        el.addEventListener(ev, f, false);
    }:window.attachEvent? function(el, ev, f){
        el.attachEvent('on' + ev, f);
    }:function(){return;};
})();
var removeEvent = (function(){return window.addEventListener? function(el, ev, f){
        el.removeEventListener(ev, f, false);
    }:window.attachEvent? function(el, ev, f){
        el.detachEvent('on' + ev, f);
    }:function(){return;};
})();

    var iframe = document.getElementById('iframe'),
        fergusonscove = document.getElementById('fergusonscove');
        herringcove = document.getElementById('herringcove');
        portugeusecove = document.getElementById('portugeusecove');
        halifaxward01 = document.getElementById('halifaxward01');


    function changeframe(){
        var iDoc = (iframe.contentWindow || iframe.contentDocument || null);
    removeEvent(iframe, 'load', changeframe);
    }
    addEvent(fergusonscove, 'click', function () {
        addEvent(iframe, 'load', changeframe);
        iframe.src = 'http://interactive.ancestry.com/8991/1921_041-E002904764/8517860#?imageId=1921_043-e002907748';
        });

        addEvent(herringcove, 'click', function () {
        addEvent(iframe, 'load', changeframe);
        iframe.src = 'http://interactive.ancestry.com/8991/1921_041-E002904764/8517860#?imageId=1921_043-e002907755';
    });

    addEvent(portugeusecove, 'click', function () {
        addEvent(iframe, 'load', changeframe);
        iframe.src = 'http://interactive.ancestry.com/8991/1921_041-E002904764/8517860#?imageId=1921_043-e002907762';
    });

        addEvent(halifaxward01, 'click', function () {
        addEvent(iframe, 'load', changeframe);
        iframe.src = 'http://interactive.ancestry.com/8991/1921_041-E002904764/8517860#?imageId=1921_043-e002908373';
    });

}); 
</script>

As you can see, I am doing everything manually for this part. As it stands now, I will have to type all of this by hand for each place name. And there will be thousands of them.

如您所见,我正在为此部分手动完成所有操作。就目前而言,我必须手动为每个地名输入所有这些内容。而且会有成千上万的人。

     var iframe = document.getElementById('iframe'),
        fergusonscove = document.getElementById('fergusonscove');
        herringcove = document.getElementById('herringcove');
        portugeusecove = document.getElementById('portugeusecove');
        halifaxward01 = document.getElementById('halifaxward01');

Etc. Etc. Then, to get the new Ancestry image, I again have to type by hand for each place.

等等。然后,为了获得新的祖先形象,我再次必须手动为每个地方打字。

    function changeframe(){
        var iDoc = (iframe.contentWindow || iframe.contentDocument || null);
    removeEvent(iframe, 'load', changeframe);
    }
    addEvent(fergusonscove, 'click', function () {
        addEvent(iframe, 'load', changeframe);
        iframe.src = 'http://interactive.ancestry.com/8991/1921_041-E002904764/8517860#?imageId=1921_043-e002907748';
        });

        addEvent(herringcove, 'click', function () {
        addEvent(iframe, 'load', changeframe);
        iframe.src = 'http://interactive.ancestry.com/8991/1921_041-E002904764/8517860#?imageId=1921_043-e002907755';
    });

Etc. Etc. Is there a way to automate this somewhat to cut down on the manual labour? Thanks in advance for any help.

等等。有没有办法自动化这种方式来减少手工劳动?在此先感谢您的帮助。

2 个解决方案

#1


1  

Basically, you need a for loop.

基本上,你需要一个for循环。

You should combine the code for one item together in one function that you then give parameters.

您应该将一个项目的代码组合在一个函数中,然后再给出参数。

The trick is to take two of those examples and look for what is different in each of them. Each thing that changes needs a parameter.

诀窍是采取其中两个例子,并寻找每个例子中的不同之处。每个改变的东西都需要一个参数。

Let's look at a simple example:

我们来看一个简单的例子:

var users = ['Alice', 'Bob', 'Charlie'];
console.log('Hello, %s!', users[0]);
console.log('Hello, %s!', users[1]);
console.log('Hello, %s!', users[2]);

This will print:

这将打印:

Hello, Alice!

你好,爱丽丝!

Hello, Bob!

你好,鲍勃!

Hello, Charlie!

你好,查理!

... but we had to write three console.log statements. No fun if there are thousands of users. Let's try to make this code more generic. First, we make a function:

...但我们必须编写三个console.log语句。如果有数千名用户,那就没有乐趣了。让我们尝试使这个代码更通用。首先,我们做一个功能:

function greet() {
    console.log('Hello, %s!', users[0]);
}

We're halfway there, but this will always print the greeting for Alice, as the users[0] part is hardcoded. This is the part we need to replace by a parameter:

我们已经到了一半,但这将始终打印Alice的问候语,因为用户[0]部分是硬编码的。这是我们需要用参数替换的部分:

function greet(name) {
    console.log('Hello, %s!', name);
}

Now, we can simply loop over our users to greet all of them, no matter how many there are:

现在,我们可以简单地循环我们的用户来迎接所有用户,无论有多少:

for (var i=0; i<users.length; i++) {
    greet(users[i]);
}

I know this isn't a copy-paste answer, but if you apply these principles and some patience you should be able to pull this off.

我知道这不是复制粘贴的答案,但如果你应用这些原则和耐心,你应该能够解决这个问题。

Good luck!

祝你好运!

#2


0  

My OCD is my downfall ... must stay away from overflow!. This would be a much cleaner way to handle the your requirements. In JS the ancestoryService() is the init fn. Addition additional object service properties is easy.

我的强迫症是我的垮台......必须远离溢出!这将是一种更清洁的方式来处理您的要求。在JS中,ancestoryService()是init fn。添加其他对象服务属性很容易。

NOTES:

笔记:

  1. I'm using lodash JS library which is must have for JS dev!
  2. 我正在使用lodash JS库,这是JS dev必备的!
  3. I use Angular JS which is great for JS OOP. Has a steep learning curve but makes for great code. React is also brilliant.
  4. 我使用Angular JS,这对JS OOP来说很棒。学习曲线陡峭,但代码很棒。 React也很棒。
  5. btw for DOM parsing take a look at JS DOM element API. I use that extensively. Example, you could build a observer service that will watch the ancestors DOM to automatically update. You can also add / extract meaningful DOM info.
  6. 用于DOM解析的btw看看JS DOM元素API。我广泛使用它。例如,您可以构建一个观察者服务,该服务将监视祖先DOM自动更新。您还可以添加/提取有意义的DOM信息。

Working Sandbox

工作沙盒

https://jsfiddle.net/nb3gmdkL/

https://jsfiddle.net/nb3gmdkL/

HTML EXAMPLE

HTML示例

    <body>
      <h1>Ancetory</h1>
      <div id="Bob" src="http://www.bob.com"></div>
      <div id="Jack" src="http://www.jack.com"></div>
      <div id="Fred" src="http://www.fred.com"></div>
      <div id="Kate"src="http://www.kate.com"></div>
      <div id="Bob"src="http://www.bob.com"></div>
    </body>

CODE

 (function() {

    function ImageService() {
      var model = this,
      item = {};

      model.setInstance = function(instance) {
         item['id'] = instance['id'] ? instance['id'] : null;
         item['url'] = instance.getAttribute("src") ? instance.getAttribute("src") : null;
      }

      model.getInstance = function(instance) {
         return item;
      }

      model.getId = function() {
         return item['id'];
      }

        model.getUrl = function() {
         return item['url'];
      }

      return {
        setInstance: function(instance) {
          model.setInstance(instance);
        },
        getInstance: function() {
          return model.getInstance();
        },
        getId: function() {
          return model.getInstance();
        },
      }
    }

    function ImageCollection() {
      var collection = this,
          store = [];

      collection.add = function(instance) {
                if (instance) {
             store.push(instance);
            } else {
            console.log('Oops, conatins', instance)
          }
      }

      collection.contains = function(instance) {
        if (store) {
          return undefined !== _.find(store, function(item, k) {
            return item.getId() == instance.getId();
          });
        }
      }

      collection.all = function() {
         return store;
      }

            return {
            add: function(instance) {
             collection.add(instance);
          },
          all: function() {
             return collection.all();
          }
        }
    }

    function ancestoryService() {
      var allElements =document.querySelectorAll('[id]');
      console.log(allElements);

      if (allElements) {
        var collection = new ImageCollection();

        _.each(allElements, function(item, key) {
          var instance = new ImageService();
          instance.setsetInstance(instance);
          console.log('get instance', instance.getId());
          console.log('get instance', instance.getUrl());
          console.log('collection add', collection.add(instance));
          console.log('collection all', collection.all());
        })
      }
    }

    ancestoryService();
    })();

#1


1  

Basically, you need a for loop.

基本上,你需要一个for循环。

You should combine the code for one item together in one function that you then give parameters.

您应该将一个项目的代码组合在一个函数中,然后再给出参数。

The trick is to take two of those examples and look for what is different in each of them. Each thing that changes needs a parameter.

诀窍是采取其中两个例子,并寻找每个例子中的不同之处。每个改变的东西都需要一个参数。

Let's look at a simple example:

我们来看一个简单的例子:

var users = ['Alice', 'Bob', 'Charlie'];
console.log('Hello, %s!', users[0]);
console.log('Hello, %s!', users[1]);
console.log('Hello, %s!', users[2]);

This will print:

这将打印:

Hello, Alice!

你好,爱丽丝!

Hello, Bob!

你好,鲍勃!

Hello, Charlie!

你好,查理!

... but we had to write three console.log statements. No fun if there are thousands of users. Let's try to make this code more generic. First, we make a function:

...但我们必须编写三个console.log语句。如果有数千名用户,那就没有乐趣了。让我们尝试使这个代码更通用。首先,我们做一个功能:

function greet() {
    console.log('Hello, %s!', users[0]);
}

We're halfway there, but this will always print the greeting for Alice, as the users[0] part is hardcoded. This is the part we need to replace by a parameter:

我们已经到了一半,但这将始终打印Alice的问候语,因为用户[0]部分是硬编码的。这是我们需要用参数替换的部分:

function greet(name) {
    console.log('Hello, %s!', name);
}

Now, we can simply loop over our users to greet all of them, no matter how many there are:

现在,我们可以简单地循环我们的用户来迎接所有用户,无论有多少:

for (var i=0; i<users.length; i++) {
    greet(users[i]);
}

I know this isn't a copy-paste answer, but if you apply these principles and some patience you should be able to pull this off.

我知道这不是复制粘贴的答案,但如果你应用这些原则和耐心,你应该能够解决这个问题。

Good luck!

祝你好运!

#2


0  

My OCD is my downfall ... must stay away from overflow!. This would be a much cleaner way to handle the your requirements. In JS the ancestoryService() is the init fn. Addition additional object service properties is easy.

我的强迫症是我的垮台......必须远离溢出!这将是一种更清洁的方式来处理您的要求。在JS中,ancestoryService()是init fn。添加其他对象服务属性很容易。

NOTES:

笔记:

  1. I'm using lodash JS library which is must have for JS dev!
  2. 我正在使用lodash JS库,这是JS dev必备的!
  3. I use Angular JS which is great for JS OOP. Has a steep learning curve but makes for great code. React is also brilliant.
  4. 我使用Angular JS,这对JS OOP来说很棒。学习曲线陡峭,但代码很棒。 React也很棒。
  5. btw for DOM parsing take a look at JS DOM element API. I use that extensively. Example, you could build a observer service that will watch the ancestors DOM to automatically update. You can also add / extract meaningful DOM info.
  6. 用于DOM解析的btw看看JS DOM元素API。我广泛使用它。例如,您可以构建一个观察者服务,该服务将监视祖先DOM自动更新。您还可以添加/提取有意义的DOM信息。

Working Sandbox

工作沙盒

https://jsfiddle.net/nb3gmdkL/

https://jsfiddle.net/nb3gmdkL/

HTML EXAMPLE

HTML示例

    <body>
      <h1>Ancetory</h1>
      <div id="Bob" src="http://www.bob.com"></div>
      <div id="Jack" src="http://www.jack.com"></div>
      <div id="Fred" src="http://www.fred.com"></div>
      <div id="Kate"src="http://www.kate.com"></div>
      <div id="Bob"src="http://www.bob.com"></div>
    </body>

CODE

 (function() {

    function ImageService() {
      var model = this,
      item = {};

      model.setInstance = function(instance) {
         item['id'] = instance['id'] ? instance['id'] : null;
         item['url'] = instance.getAttribute("src") ? instance.getAttribute("src") : null;
      }

      model.getInstance = function(instance) {
         return item;
      }

      model.getId = function() {
         return item['id'];
      }

        model.getUrl = function() {
         return item['url'];
      }

      return {
        setInstance: function(instance) {
          model.setInstance(instance);
        },
        getInstance: function() {
          return model.getInstance();
        },
        getId: function() {
          return model.getInstance();
        },
      }
    }

    function ImageCollection() {
      var collection = this,
          store = [];

      collection.add = function(instance) {
                if (instance) {
             store.push(instance);
            } else {
            console.log('Oops, conatins', instance)
          }
      }

      collection.contains = function(instance) {
        if (store) {
          return undefined !== _.find(store, function(item, k) {
            return item.getId() == instance.getId();
          });
        }
      }

      collection.all = function() {
         return store;
      }

            return {
            add: function(instance) {
             collection.add(instance);
          },
          all: function() {
             return collection.all();
          }
        }
    }

    function ancestoryService() {
      var allElements =document.querySelectorAll('[id]');
      console.log(allElements);

      if (allElements) {
        var collection = new ImageCollection();

        _.each(allElements, function(item, key) {
          var instance = new ImageService();
          instance.setsetInstance(instance);
          console.log('get instance', instance.getId());
          console.log('get instance', instance.getUrl());
          console.log('collection add', collection.add(instance));
          console.log('collection all', collection.all());
        })
      }
    }

    ancestoryService();
    })();