我读过的所有内容都说要使用 element.onclick 属性,但这似乎不适用于我的情况。我正在尝试解析数字:629216818 并将其设置为变量:fbid。这是一个 Greasemonkey 脚本,因此无法直接编辑 HTML。我不是专业人士,所以我可能只是做了一些愚蠢的事情,但这是我的 HTML 和 Javascript:
<div id="petRightContainer">
<a title = "Pet trainer bonus: Your companion will level 5% faster." href="setup.php?type=companion>Random=8167343321487308">
<div class="petRight" style="background-image:url(/fb/res/gui4/companion/cu_sith.jpg)"></div>
</a>
<div class="petRightLevel">
<a href="#" onClick="publishToWall('http://www.ghost-trappers.com/fb', 'Look at the cool augmentations my companion has received on Ghost Trappers.', 'Look at my new companion on Ghost Trappers! I\'ve named it Jankie. ', null, 'index.php?si=629216818&fromWall=1', 'white/companion_32.jpg', 'companion/wallpost_augmentation_12.jpg', 'companion/wallpost_augmentation_21.jpg', 'companion/wallpost_augmentation_11.jpg', null)">Dog</a>
</div>
等等
<script type="text/javascript">
fbid = 0;
fbidRegex = /\d{3,}(?=&fromWall=1)/;
if ( document.getElementsByClassName("petRightLevel")[0]){
element = document.getElementsByClassName("petRightLevel")[0].firstChild;
codeStore = element.onclick;
fbid = fbidRegex.exec(codeStore);
document.write("it is working ");
}
document.write(fbid);
</script>
最佳答案
问题出在这一行:
element = document.getElementsByClassName("petRightLevel")[0].firstChild;
如果您使用的是 Firefox 和其他支持 document.getElementsByClassName
的浏览器在 HTML 中, <div class="petRightLevel">
之间有空格和
<a href="#" onClick= ...>
,firstChild实际上是一个文本节点而不是链接。您需要做的就是删除两个元素之间的空格和/或换行符。
如果您使用 IE,问题仍然出在 JavaScript 的同一行,因为 IE 在版本 8 之前不支持 document.getElementsByClassName。
更新:以下 JavaScript 代码适用于我测试的所有浏览器,无需接触 HTML:
<script type="text/javascript">
fbid = 0;
fbidRegex = /\d{3,}(?=&fromWall=1)/;
var divs = document.getElementsByTagName("div");
var link = null;
for (var i=0;i<divs.length;i++)
{
if(divs[i].getAttribute("class") ==="petRightLevel")
{
link = divs[i].getElementsByTagName("a")[0];
break;
}
}
if (link){
codeStore = link.onclick;
fbid = fbidRegex.exec(codeStore);
document.write("it is working ");
}
document.write(fbid);
</script>
如果只需要获取 anchor ,会比这简单得多。
关于javascript - 无法使用 DOM 解析 onClick 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10763337/