一段时间循环会更好吗?这看起来多余吗?

时间:2016-10-26 21:45:47

标签: php jquery loops refactoring

我正在尝试创建一个随机的背景图像选择器。我的工作,但似乎笨重和多余。我能帮助找出一个更好的方法来写这个吗?

要求:

  • 每次页面都应显示页面的随机背景 刷新。
  • 每个背景都有一个特定的文本模糊,所以 每个背景都需要显示正确的文字。
  • 列出一系列链接以显示其他背景/文字 目前显示的背景/文字不应列在 索引。

示例:如果正在显示background3.jpg,则列表应该只有background1.jpg,background2.jpg和background4.jpg。

PHP

  $backgrounds = 
  array(
  'cat1.jpg', 'cat2.jpg', 'cat3.jpg', 'cat4.jpg', 'cat5.jpg', 'cat6.jpg'); // array of image files

  $randBg = rand(0, count($backgrounds)-1); // generate random number size of the array
  $selectedBg = "$backgrounds[$randBg]"; // set variable equal to which random filename was chosen

  $strings = array('This kitten has a filter', 'This cat is in the dark', 'This kitten has green eyes', 'This cat has a mask', 'This is Grumpy Cat', 'This cat is orange'); // array of strings, that correspond to each image

  function showString($backgrounds, $randBg, $strings) {
    for ($b = 0; $b < count($backgrounds); $b++) {
        if ($b == $randBg) {
            echo $strings[$b]; // Loop through the image array and print corresponding text from strings array
        }
    }
  }

HTML

<div id="text">
    <h1><?php showString($backgrounds, $randBg, $strings); ?></h1>
</div>
<div id="index">
    <ul>
        <li id="1">Filter</li>
        <li id="2">The dark</li>
        <li id="3">Green eyes</li>
        <li id="4">Mask</li>
        <li id="5">Grumpy</li>
        <li id="6">Orange</li>
    </ul>
</div>

CSS

body {
    /* randomly selected background image */
    background-image: url(images/<?php echo $selectedBg; ?>); 
    background-size: cover;
    background-repeat: no-repeat;
}

div#text { /* the text from the respective background image goes in this div */
    background-color: rgba(255, 255, 255, 0.8);
    width: 50%;
    margin: 10% auto 0 auto;
    display: block;
    text-align: center;
    padding: 25px;
}

div#text h1 {
    color: #000;
}

div#index { /* use this menu to view other background images */
    background-color: rgba(255, 255, 255, 0.8);
    width: 50%;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    bottom: 0;
}

div#index ul {
    list-style-type: none;
    overflow: hidden;
}

div#index ul li {
    float: left;
    padding: 25px;
}

div#index ul li:hover {
    background-color: #000;
    color: #fff;
    cursor: pointer;
}

jQuery

var selected = $("li"); // make var for the list items
var bgsArray = [1, 2, 3, 4, 5, 6]; // make array of backgrounds
var strings = [ // make array of strings
    "This kitten has a filter", 
    "This cat is in the dark", 
    "This kitten has green eyes", 
    "This cat has a mask", 
    "This is Grumpy Cat", 
    "This cat is orange"
    ];
var current = bgsArray[Math.floor(Math.random() * bgsArray.length)]; // get a background image randomly (can't be anything else or else the initial image is always the same on reload).
if ($("body").css("background-image", "url('images/cat" + current + ".jpg')")) { // check current background image against the random number
    $("div#text h1").html("" + strings[current - 1]); // make sure correct text displays
    $("li#" + current).css("display", "none"); // hide current displaying bg in index
    $("li#" + current).siblings().css("display", "block"); // make sure all other index values are showing
}

$.each(selected, function() { // function to iterate through all list items
    selected.click( function() { // function for clicking on list item

        var li_id = $(this).prop("id"); // get the id of the <li> that was just clicked
        var cssBg = "url('images/cat" + li_id + ".jpg')"; // create string for bg url with id
        $("body").css("background-image", cssBg); // change page bg to new image with corresponding id
        $("div#text h1").html("" + strings[li_id - 1]); // change the text
        if ($("body").css("background-image", cssBg)) { // hide the <li> for the bg that's currently displaying, but show all others
            $("li#" + li_id).css("display", "none");
            $("li#" + li_id).siblings().css("display", "block");
        }
    });
});

我的目标是学习如何概念化重构(如果这有意义),因为我知道有一种更简洁的方式来编写它。 PHP和jQuery都需要吗?我应该使用AJAX吗?我使用jQuery在初始页面加载后最小化HTTP请求。如果使用一种语言效率更高,我宁愿这样做。感谢您提供任何帮助。

3 个答案:

答案 0 :(得分:1)

  1. 如果您知道数组中元素的key - 您不需要遍历键来获取值,您只需获取值:

  2. function showString($backgrounds, $randBg, $strings) {
        echo $strings[$randBg]; // Loop through the image array and print corresponding text from strings array
    }
    
    1. 函数mt_rand优于rand。

    2. $randBg = mt_rand(0, count($backgrounds)-1);
      
      1. 如果您想从数组中获取随机元素,可以使用array_rand函数:

      2. $key = array_rand($backgrounds);
        $backgrounds[$key]; // this is the random-background you want
        

答案 1 :(得分:1)

从您的描述中不完全确定,但似乎您不需要PHP。您只需使用JS即可显示随机图像。此外,使用地图将图像连接到文本的模糊是更清洁。

例如:

var imageToText = {
 "imageNameA": "cat text A", 
 "imageNameB": "cat text B",
 ... 
}

flow:根据地图的大小,获取imageName +对应的文本

另外,稍微谈论事件处理程序

你有:

var selected = $("li"); // make var for the list items
...
$.each(selected, function() { // function to iterate through all list items
    selected.click( function() { // function for clicking on list item
    ...
   })
 })

这可以重构为:

$("li").click(function(){
  var $el = $(this);
  //do something... 
})

HTH

答案 2 :(得分:0)

$h1 = $strings[$randBg];//will return correct string for the BG