【问题标题】:javascript. my for loop stops after one iteration when enclosed in a functionjavascript。当包含在函数中时,我的 for 循环在一次迭代后停止
【发布时间】:2011-09-12 09:08:42
【问题描述】:

这是我的问题。当我的代码嵌入到 html 页面中,在 body 标记之间时,它会按预期执行:显示 12 行文本(for 循环执行 12 次);

但是,当我将代码包含在一个函数中,从外部 js 文件中导入它,并尝试使用 onclick 或 onsubmit 事件来调用它时,它会在第一次迭代后停止。

这是嵌入在 html 文件中的代码:

var all_imgs = document.getElementsByTagName('img');

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

            var item = all_imgs[i].src;
            var item_limit = item.length-4;
            var item_limit2 = item.length-6;

            var selected = item.substring(item_limit, item_limit2);

            if (selected == 'on') {
                document.write('image ' + i + ' with url : ' + item + ' is ');
                document.write('chosen');
                document.write('<br>');
            }
            else {
                document.write('image ' + i + ' with url : ' + item + ' is ');
                document.write('not chosen');
                document.write('<br>');
            }

        }  

和输出:

image 0 with url : www.../thumb2_on.jpg is CHOSEN  
image 1 with url : www.../thumb2_off.jpg is NOT CHOSEN  
image 2 with url : www.../thumb2_off.jpg is NOT CHOSEN  
image 3 ...  
.  
.  
.  
image 11 with url : www.../thumb2_on.jpg is CHOSEN  

这是来自外部 js 文件的代码:

function selectedImages(){
        var all_imgs = document.getElementsByTagName('img');

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

            var item = all_imgs[i].src;
            var item_limit = item.length-4;
            var item_limit2 = item.length-6;
            //document.write(item_limit);
            //document.write(item_limit2);

            var selected = item.substring(item_limit, item_limit2);

            if (selected == 'on') {
                document.write('image ' + i + ' with url : ' + item + ' is ');
                document.write('chosen');
                document.write('<br>');
            }
            else {
                document.write('image ' + i + ' with url : ' + item + ' is ');
                document.write('not chosen');
                document.write('<br>');
            }

        }
    }

来自 html 文件的 onclick 事件:

<a href="#" onclick="javascript:selectedImages();">test</a>

<form action="#" method="post" onsubmit="javascript:selectedImages();">

然后打印出来:

带有 url 的图片 0 : www.../thumb2_on.jpg 是选择的

【问题讨论】:

    标签: javascript loops for-loop


    【解决方案1】:

    这是因为您在页面加载后使用document.write。它将用新内容替换当前页面,因此当您进入循环中的第二次迭代时,页面中不再有任何图像。

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多