<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
细分
创建一个包含三个字符串的数组字面量:
var phrases = [
'This is the first one',
'This is the second one',
'This is the third one'
];
在页面上获取所有script elements 中的NodeList(因为页面已经加载到这一点,所以之前和包括这个的所有脚本):
var scripts = document.getElementsByTagName('script');
将该列表中的最后一个脚本(即,此脚本元素)存储在this_script:
var this_script = scripts[scripts.length - 1];
我将把下一行分成更小的部分。
Math.random 在0(包括)和1(不包括)之间给出Number。将它乘以 3 可以在 0(包括)和 3(不包括)和 Math.floor 之间截断它。这给出了一个介于 0 和 2 之间的随机整数。如果将元素添加到数组中,它将更新,因为它在计算中使用了phrases.length,而不是文字 3:
Math.floor(Math.random()*phrases.length)
document.createTextNode 创建并返回一个实现 Text 接口的新节点,它的数据就是传入的值。在这种情况下,它是短语数组中的一个随机元素:
document.createTextNode(phrases[Math.floor(Math.random()*phrases.length)])
Node.parentNode 是不言自明的,在这种情况下,脚本元素的父级将是 HTMLAnchorElement(由树中脚本上方的 <a> 标记表示)。 Node.replaceChild 接受两个参数,一个 new_child 和一个 old_child。我们为new child 传入了新的文本节点,为old_child 传入了这个脚本,这会导致这个脚本从DOM 中移除并替换为文本节点:
this_script.parentNode.replaceChild(document.createTextNode(phrases[Math.floor(Math.random()*phrases.length)]), this_script);