<a href="http://testpage.com/">
<script type="text/javascript">
// This script will replace itself with a random one of these phrases
var phrases = [
'This is the first one',
'This is the second one',
'This is the third one'
];
var scripts = document.getElementsByTagName('script');
var this_script = scripts[scripts.length - 1];
this_script.parentNode.replaceChild(document.createTextNode(phrases[Math.floor(Math.random()*phrases.length)]), this_script);
</script>
</a>
JSFiddle
壊す
3 つの文字列を含む配列リテラルを作成します。
var phrases = [
'This is the first one',
'This is the second one',
'This is the third one'
];
ページ上のすべてのスクリプト要素のNodeListを取得します (ページはこの時点まで読み込まれているため、これより前のすべてのスクリプトとこれを含むスクリプト)。
var scripts = document.getElementsByTagName('script');
そのリストの最後のスクリプト(つまり、このスクリプト要素)を次の場所に保存しますthis_script
。
var this_script = scripts[scripts.length - 1];
この次の行を小さなセグメントに分割します。
Math.randomは、(含む) と(含まない)の間の数値を返します。それに 3 を掛けると、(包括的) と(排他的) の間で均等な分布が得られ、 Math.floorはそれを切り捨てます。これにより、 ~の間のランダムな整数が得られます。配列に要素を追加すると、リテラル 3 の代わりに、計算で phrases.length を使用するため、配列が更新されます。0
1
0
3
0
2
Math.floor(Math.random()*phrases.length)
document.createTextNodeは Text インターフェースを実装する新しい Node を作成して返します。そのデータは、渡された値にすぎません。この場合は、フレーズ配列からのランダムな要素です。
document.createTextNode(phrases[Math.floor(Math.random()*phrases.length)])
Node.parentNodeは一目瞭然です。この場合、スクリプト要素の親はHTMLAnchorElement<a>
になります (ツリー内のスクリプトの上のタグで表されます)。Node.replaceChildnew_child
は、 aと an の2 つの引数を取りますold_child
。に新しいテキスト ノードを渡し、new child
にこのスクリプトを渡しましたold_child
。これにより、このスクリプトが DOM から削除され、テキスト ノードに置き換えられます。
this_script.parentNode.replaceChild(document.createTextNode(phrases[Math.floor(Math.random()*phrases.length)]), this_script);