简体   繁体   English

遍历数组并使用每个数组值更改一个html元素

[英]Looping through an array and changing an html element with each array value

I am pulling in a PHP encoded JSON string, and I am having a hard time getting the Javascript to work how I need it. 我输入了一个PHP编码的JSON字符串,并且很难使Javascript能够按需要工作。 Let me explain a bit what I am trying to do. 让我解释一下我要做什么。 I have an image I am trying to change every 20 seconds along with accompanying text. 我有一张图片,尝试每20秒更改一次,并附上文字。 I am having an issue with getting the Looping part working in my javascript code. 我在让JavaScript程序中的Looping部分工作时遇到问题。

Here is my PHP: 这是我的PHP:

public function pull_projects() {
        $sql = $this->db->query("SELECT * FROM project_table LIMIT 4");
        $project_title_array = array();
        $project_sub_title_array = array();
        $project_description_array = array();
        $project_picture_url_array = array();
        foreach($sql->result() as $row) {
            array_push($project_title_array,$row->project_title);
            array_push($project_sub_title_array,$row->project_sub_title);
            array_push($project_description_array,$row->project_description);
            array_push($project_picture_url_array,$row->project_picture_url);
        }
        echo json_encode(array('project_title' => $project_title_array, 'project_sub_title' => $project_sub_title_array, 'project_description' => $project_description_array, 'project_picture_url' => $project_picture_url_array));
    }

The above code outputs: 上面的代码输出:

{  
   "project_title":[  
      "1 STOP RADIO 85.9",
      "Official Slimm",
      "The Lab Community Foundation",
      "Official Michael Wyatt"
   ],
   "project_sub_title":[  
      "www.1stopradio859.com",
      "www.officialslimm.com",
      "www.thelabcommunityfoundation.org",
      "www.officialmichaelwyatt.com"
   ],
   "project_description":[  
      "Bon App\u00e9tit and epicurious.com joined forces to create an irresistible marketing group called FIG. We brought it to the web for our agency partners Independent Content, creating a rich and immersive online experience that delivers their powerful marketing capabilities to potential clients.",
      "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries.",
      "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries.",
      "Bon App\u00e9tit and epicurious.com joined forces to create an irresistible marketing group called FIG. We brought it to the web for our agency partners Independent Content, creating a rich and immersive online experience that delivers their powerful marketing capabilities to potential clients."
   ],
   "project_picture_url":[  
      "1stopradio859com.png",
      "officialslimmcom.png",
      "thelabcommunityfoundationorg.png",
      "officialmichaelwyattcom.png"
   ]
}

My Javascript code: 我的Javascript代码:

$.getJSON("Home/pull_projects", function(data) {

            // Sets global variables for returned json data
            window.$project_title = data.project_title;
            window.$project_sub_title = data.project_sub_title;
            window.$project_description = data.project_description;
            window.$project_picture_url = data.project_picture_url;

            // Turns returned json data into an array
            window.$project_picture_url_array = $.map(window.$project_picture_url, function(el) { return el; });

            window.$project_sub_title_array = $.map(window.$project_sub_title, function(el) { return el; });

            // Loops through and changes each value
            window.$project_picture_url_array.forEach(function(current_value, index, initial_array) {
                setTimeout(function() {
                    console.log(current_value);
                    $('.website_slider > .slider').attr('src','assets/'+current_value);
                }, 5000);
            });
});

My problem is in the ForEach statement in my javascript. 我的问题出在我的JavaScript中的ForEach语句中。 When I run it, it outputs the following in the Chrome Terminal: 当我运行它时,它会在Chrome终端中输出以下内容:

1stopradio859com.png
officialslimmcom.png
thelabcommunityfoundationorg.png
officialmichaelwyattcom.png

I need it to run and only output one value every 20 seconds not all at once. 我需要它运行,并且每20秒仅输出一个值,而不是一次全部输出。 Any help would be appreciated. 任何帮助,将不胜感激。

setTimeout is not a blocking call. setTimeout不是阻塞调用。 The loop will continue to iterate over the collection. 循环将继续遍历集合。 All callbacks will fire within a small amount of time between each other instead of over an interval. 所有回调将在彼此之间的一小段时间内触发,而不是在一定间隔内触发。 Use setIntveral instead: 使用setIntveral代替:

 var myArray = ['a', 'b', 'c', 'd', 'e']; var index = 0; var x; function printNextValue() { console.log(myArray[index]); index = (index + 1) % myArray.length; } // This will execute every second until all array elements are printed. printNextValue(); x = setInterval(printNextValue, 1000); 

Here is some sample Javascript code to show one image name every second 这是一些示例Javascript代码,每秒显示一个图像名称

var arr = [
    "1stopradio859com.png",
    "officialslimmcom.png",
    "thelabcommunityfoundationorg.png",
    "officialmichaelwyattcom.png"
];

var counter = 0;

window.setInterval( function() {
    console.log( arr[ counter++ % arr.length ] );
}, 1000 );

How about this solution. 这个解决方案怎么样。 Hope it helps! 希望能帮助到你!

 var arr = ["1stopradio859com.png" , "officialslimmcom.png", "thelabcommunityfoundationorg.png", "officialmichaelwyattcom.png"]; $("#test").html(arr[0]).fadeTo(100, 0.1).fadeTo(200, 1.0); var str = ""; var counter = 1; var timer = setInterval(function() { if(counter == 0){str = arr[counter]} if(counter == 1){str = arr[counter]} else if(counter == 2){str = arr[counter]} else if(counter == 3){str = arr[counter]} $("#test").html("<div>"+ str+"</div>").fadeTo(100, 0.1).fadeTo(200, 1.0); ++counter; if(counter == 4){ counter = 0; } }, 2000); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div id = "test"> </div> 

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

相关问题 遍历数组并将每个值除以100 - Looping Through An Array and Dividing Each Value By 100 NodeJS - 在数组中的每个元素之间按顺序循环遍历数组 - NodeJS - Looping through Array Sequentially with Timeout between each Element in Array 通过遍历数组来更改innerHTML - Changing innerHTML by looping through an array 循环遍历并将每个表行td元素值存储为对象数组 - Looping through and storing each table row td element value as array of objects 循环遍历数组并作为对输出(每个第二个元素的分隔符) - Looping through array and output as pairs (divider for each second element) 循环遍历数组并将每个元素设置为 object 的属性会导致顺序混乱 - Looping through an array and setting each element as a property of an object messes with the order 遍历 JSON 并在 HTML 表格中显示每个数组项 - Looping through JSON and display each array item in HTML table 循环到每个元素的数组方法 - Array Method for looping to each element 遍历对象数组并返回每个 object 的键和值 - Looping through array of objects and return the key and value for each object 循环遍历数组中的元素并查找它出现的次数并添加其他元素并推入新数组 - Looping through elements in an array and finding how many times it appears and adding each other element and pushing into a new array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM