令人困惑的一点,试图使用https://craig.is/killing/mice捕鼠器为我的页面上的某些网址添加键盘快捷键。
我有这个来设置键:
Mousetrap.bind('up', function() { document.getElementById("n").click(); });
Mousetrap.bind('down', function() { document.getElementById("s").click(); });
Mousetrap.bind('left', function() { document.getElementById("w").click(); });
Mousetrap.bind('right', function() { document.getElementById("e").click(); });
Mousetrap.bind('e', function() { document.getElementById("gatherEnergy").click(); });
然后用于箭头键的html工作正常:
<area id="n" alt="North" title="North" href="#" onclick="moven();refreshIframe();" shape="poly" coords="49,1,50,45,113,45,110,1" />
<area id="e" alt="East" title="East" href="#" onclick="movee();refreshIframe();" shape="poly" coords="118,52,156,53,156,113,118,115" />
<area id="w" alt="West" title="West" href="#" onclick="movew();refreshIframe();" shape="poly" coords="42,52,0,51,1,115,40,117" />
<area id="s" alt="South" title="South" href="#" onclick="moves();refreshIframe();" shape="poly" coords="49,126,51,164,114,165,112,127" />
哪一切都运行正常并按预期按下箭头键点击网址,但是当我到达键时,#34; e&#34;我使用的是href而不是某个区域:
<a href="map.php?act=e" id="gatherEnergy" onclick="refreshIframe();">Gather energy</a>
这会返回错误:Uncaught TypeError: Cannot read property 'click' of null
document.getElementById(#ID).click();由于某种原因不能在href上工作?或者我是不是很好?真的很困惑这个,所以任何建议都会很棒!
编辑: 设置一个jsfiddle与它https://jsfiddle.net/Lek3ptvp/,这是有效的!
在我的本地主机上,我试图触发的网址是iframe,这会导致问题吗?如何在iframe中创建.document.getElementById?
答案 0 :(得分:-1)
编辑:由于您拥有内容,请尝试以下内容:
document.getElementById("myiframe").contentWindow.document.getElementById("gatherEnergy").click();
在我的localhost上,我试图触发的网址是iframe,
只要尝试进行交互的页面和您加载的页面具有相同的document.domain,浏览器就会允许您与iframe进行交互。显然不是这样的
https://jsfiddle.net/05b8sjy3/
<iframe src="www.google.com">
</iframe>
setTimeout(_ =>document.getElementById("sidebar").click(),2000);
您不希望网站代表用户在www.mybank.com上进行操作。