javascript.当包含在函数中时,我的for循环在一次迭代后停止

javascript. my for loop stops after one iteration when enclosed in a function

本文关键字:一次 迭代 for 函数 包含 javascript 我的 循环      更新时间:2023-09-26

我的问题是。当我的代码嵌入到html页面中,在正文标记之间,它按照假定的方式执行:显示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();">

和打印输出:

image 0 with url: www.../thumb2_on.jpg is CHOSEN

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