【发布时间】:2016-07-11 23:53:26
【问题描述】:
我有一个嵌入框架元素的书籍列表。我想退回其中三本书并将它们插入到我已经定义的div 中。我正在尝试使用 shuffle 方法,但由于无法让元素显示或随机化,因此出现了问题。
下面的代码是我正在尝试使用的示例。
Javascript
function randomBooks(arr, count) {
var arr = [ // list of books
'<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="https://read.amazon.com/kp/card?asin=B00ARFNQ54&asin=B00ARFNQ54&preview=newtab&linkCode=kpe&ref_=cm_sw_r_kb_dp_wpdGxbH9ZAXX9&hideShare=true" ></iframe>',
'<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="https://read.amazon.com/kp/card?asin=B00AFH1TBC&asin=B00AFH1TBC&preview=newtab&linkCode=kpe&ref_=cm_sw_r_kb_dp_5udGxbAPXN07Q&hideShare=true" ></iframe>',
'<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="https://read.amazon.com/kp/card?asin=B005GSYZRA&asin=B005GSYZRA&preview=inline&linkCode=kpe&ref_=cm_sw_r_kb_dp_FxdGxbYXKDM2P&hideShare=true" ></iframe>',
'<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="https://read.amazon.com/kp/card?asin=B00ARFNQ54&asin=B00ARFNQ54&preview=newtab&linkCode=kpe&ref_=cm_sw_r_kb_dp_wpdGxbH9ZAXX9&hideShare=true" ></iframe>',
'<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="https://read.amazon.com/kp/card?asin=B00AFH1TBC&asin=B00AFH1TBC&preview=newtab&linkCode=kpe&ref_=cm_sw_r_kb_dp_5udGxbAPXN07Q&hideShare=true" ></iframe>',
'<iframe type="text/html" width="150" height="200" frameborder="0" allowfullscreen style="max-width:100%" src="https://read.amazon.com/kp/card?asin=B005GSYZRA&asin=B005GSYZRA&preview=inline&linkCode=kpe&ref_=cm_sw_r_kb_dp_FxdGxbYXKDM2P&hideShare=true" ></iframe>'
];
var insertDiv = document.getElementsByClassName("bookFrame"); // Div I want elements inserted
var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
var returnedValue= shuffled.slice(min, 3);
insertDiv.innerHTML(returnedValue); // inject 3 random book elements
alert( randomBooks(arr, 3)); // Checking
};
HTML
<p class="center bookFrame">
<!-- Insert books here -->
</p>
【问题讨论】:
标签: javascript arrays sorting random