-1

我正在使用 Ionic 1 / Cordova。我正在尝试从数组中选择一个随机图像以显示在页面上(以便每次用户访问时它都不同)。我让它每次从数组中随机选择一个 URL,但它会在停止之前翻阅页面上的 3 或 4 个图像。我知道这是 ng-src 的预期摘要行为,但是在第一个周期后如何防止或停止它?

HTML:

<md-list-item flex layout="column" layout-align="center">
    <div layout="row" layout-align="center center">
      <img class="logo" ng-src="{{resultgif(url)}}"/>
    </div>
</md-list-item>

.js:

$scope.resultgif = function(url) {

   {
  var answers = [
"images/1500.gif",
"images/1500.gif",
"images/2000.gif",
"images/2500.gif",
"images/3000.gif",
"images/3500.gif",
"images/4000.gif",
"images/4500.gif"
]

var randomAnswer = answers[Math.floor(Math.random() * answers.length)];

};

  return randomAnswer;
  }
4

2 回答 2

1

据我了解,您正试图让所有内容每个周期仅显示一次。我不是为角度设置的,但这里有一个模拟函数可以帮助你。对于 Angular,您可能必须包含 $window 才能访问 localStorage,否则这将适用于 vanilla js

    const answers = [
    "images/1500.gif",
    "images/1500.gif",
    "images/2000.gif",
    "images/2500.gif",
    "images/3000.gif",
    "images/3500.gif",
    "images/4000.gif",
    "images/4500.gif"
];


let randomImage = function (staticArray = [], storeName = "store") {
    let result = '';
    let _seen = localStorage.getItem(storeName);
    let _seenArr = JSON.parse(_seen);
    let allArr = [];
    staticArray.forEach(function (element, index) {
        allArr.push(index);
    });

    let rIdx = Math.floor(Math.random() * staticArray.length);


    if (_seen === null) {
        localStorage.setItem(storeName, JSON.stringify([rIdx]));
        result = staticArray[rIdx];
    } else {

        let _unseen = allArr.filter((el) => !_seen.includes(el));
        rIdx = Math.floor(Math.random() * _unseen.length);
        result = staticArray[_unseen[rIdx]];
        _seenArr.push(_unseen[rIdx]);
        localStorage.setItem(storeName, JSON.stringify(_seenArr));
        result = staticArray[_unseen[rIdx]];

        if (JSON.parse(localStorage.getItem(storeName)).length >= staticArray.length) {
            localStorage.removeItem(storeName);
        }


    }

    return result;
};


console.log(randomImage(answers));
于 2018-06-15T23:39:09.147 回答
0

我通过创建一个分离函数来首先选择图像然后调用该变量来使其工作。它现在每次加载 1 个随机图像。这是更新的 JS,以防它帮助其他人。

 var winningGif = null;

 $scope.resultgif = function() {

  var sendGif = winningGif;
  return sendGif;

  };

function getRandomGif()     {

  var answers = [
"images/1500.gif",
"images/1500.gif",
"images/2000.gif",
"images/2500.gif",
"images/3000.gif"

]

 var randomAnswer = Math.floor(Math.random() * answers.length);
 winningGif = answers[randomAnswer];

}     
于 2018-06-16T10:13:51.127 回答