简体   繁体   English

javascript for循环的问题不在每次执行时

[英]issue with javascript for loop not executing every time

I'm using this JavaScript code for alert count in an array of pages. 我正在将此JavaScript代码用于页面数组中的警报计数。

urls is an array of page names, and count is the count value. urls是页面名称的数组,count是计数值。

I want to alert the count value in each pages of the array urls. 我想提醒数组网址的每个页面中的计数值。

But the for loop is not executing all time. 但是for循环并非一直执行。 I don't know what happens... Any body please help me to find out the mistake.. 我不知道会发生什么...任何人请帮助我找出错误。

Am using echo $_POST['suggest']; 我正在使用echo $_POST['suggest']; in the array of pages. 在页面数组中。 But i want to use JavaScript code for receiving the value of suggest and alert it. 但是我想使用JavaScript代码来接收建议的值并发出警报。 How to receive the value using JavaScript? 如何使用JavaScript接收值?

<script>
        $(document).ready(function () {
            var count = document.getElementById('display_visitor_number').innerHTML; //count
            var urls = document.getElementById('display_visitor_urls').innerHTML; //array of page names
            var myarr = urls.split(",");

            for (var i=1;i<myarr.length;i++)
            { 
                $.post(myarr[i],{suggest:count}, function(data) {
                    alert(data);
                });
            }


        });
    </script>

if the string urls starts with , before you split it will have an empty string as first value (this will cause jquery to make an ajax call for the current page) you may want to check for that and start with 0 如果字符串url以开头,则在拆分之前它将有一个空字符串作为第一个值(这将使jquery对当前页面进行ajax调用),您可能需要检查并从0开始

<script>
        $(document).ready(function () {
            var count = document.getElementById('display_visitor_number').innerHTML; //count
            var urls = document.getElementById('display_visitor_urls').innerHTML; //array of page names
            var myarr = urls.split(",");

            for (var i=0;i<myarr.length;i++)
            { 
                if(myarr[i] !== '')$.post(myarr[i],{suggest:count}, function(data) {
                    alert(data);
                });
            }


        });
    </script>

instead of using split function you'd better try RegExp and match all non-space character sequences. 最好使用RegExp并匹配所有非空格字符序列,而不是使用split函数。 replace 更换

var myarr = urls.split(",");

with

var myarr = urls.match(/[^ ,]+/g)

and you should start you for loop with var i=0 then. 你应该开始你for带环var i=0即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM