埋め込みフレーム要素の書籍のリストがあります。私はそれらの本のうちの3つを返して、既に定義したdiv
に挿入したいと思っています。私はシャッフル方法を利用しようとしていますが、要素を表示またはランダム化することができないので、何かがうまくいかない。ランダムなn個の要素の配列をとり、指定された要素に挿入します。
以下のコードは、私が使用しようとしている例です。
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>
これはこれを行うのは本当にスマートな方法です!書籍のIDを配列内の唯一のアイテムにすることは良いステップです。非常に明確で説明された答えをありがとう。 – privateer35