1

私が持っているリストからページがランダムに更新されるたびに変更される1つのアンカータグを作成する方法を見つけようとしています。

このリストを持っているとしましょう

<a href="http://testpage.com/">This is the first one</a>
<a href="http://testpage.com/">This is the second one</a>
<a href="http://testpage.com/">This is the third one</a>

これが1枚目 これが2枚目 これが3枚目

これは Adsense のリンク ユニット広告のようなものですが、トピックに関連しているかどうか、または AdSense とは異なるかどうかを確認するなどの余分な作業を行わないように、単純なランダム処理を実行したいだけです。

私に何ができるかアドバイスしてください。

ありがとう

4

2 に答える 2

2
<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 を使用するため、配列が更​​新されます。010302

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);
于 2012-06-01T01:46:04.800 に答える
1

次のように php を使用できます。

<?php $linkName = mt_rand(1,3);
 if ($linkName == 1) echo '<a href="http://testpage.com/">This is the first one</a>';
 if ($linkName == 2) echo '<a href="http://testpage.com/">This is the second one</a>';
 if ($linkName == 3) echo '<a href="http://testpage.com/">This is the third one</a>';
?>
于 2012-06-01T01:58:53.103 に答える