为什么这个bookmarklet JS代码放在onclick处理程序中不起作用? [英] Why does this bookmarklet JS code not work when put in an onclick handler?

查看:138
本文介绍了为什么这个bookmarklet JS代码放在onclick处理程序中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常典型的书签代码,在所有浏览器中都能为我工作。
但是,当我把这个代码放在HTML的元素onClick处理程序中,它在IE(6,7或8)中不起作用。

I have a pretty typical bookmarklet code that's working perfectly for me in all browsers. However, when I take this code and put it in an HTML's element onClick handler, it doesn't work in IE (6, 7, or 8).

这是代码:

javascript: (
    function(){
        function l(i,u){
            var d=document;
            var s;
            try{
                s=d.standardCreateElement('script');
            }catch(e){}
            if(typeof(s)!='object')
                s=d.createElement('script');
            try{
                s.type='text/javascript';
                s.src='http://{Domain}/bk/' + u;
                s.id='s_' + i;
                d.getElementsByTagName('head')[0].appendChild(s);
            }catch(e){
            }
        }
        AppD = '{Domain}';          
        l('b', 'bk.js');
    }   
    )();

压缩为书签,看起来像:

Compressed down as a bookmarklet, that looks like:

javascript:function(){function l(i,u){var d=document;var s;try{s=d.standardCreateElement('script');}catch(e){} if(typeof(s)!='object')  s=d.createElement('script'); try{s.type='text/javascript';s.src='http://{Domain}/bk/' + u;s.id='s_' + i;d.getElementsByTagName('head')[0].appendChild(s);}catch(e){}}AppD = '{Domain}';l('b', 'bk.js');})();

这样很好用。
我已经取出了javascript:前缀,并将其放入元素的onClick中:

And that works perfectly. I've taken out the javascript: prefix, and put it into an element's onClick:

<img onclick="function(){function l(i,u){var d=document;var s;try{s=d.standardCreateElement('script');}catch(e){} if(typeof(s)!='object')   s=d.createElement('script'); try{s.type='text/javascript';s.src='http://{Domain}/bk/' + u;s.id='s_' + i;d.getElementsByTagName('head')[0].appendChild(s);}catch(e){}}AppD = '{Domain}';l('b', 'bk.js');})();" />

除了IE之外,bk.js中的代码(脚本,被注入)抱怨该变量AppD没有定义...

And that works well too, except than in IE, the code inside bk.js (the script that gets injected) complains that variable AppD is not defined...

任何想法为什么会发生这样的事情?

对代码有任何限制可以放入onClick处理程序?

Any ideas why this is happening?
Is there any limitation to the code one can put in an onClick handler?

谢谢!
Daniel

Thanks! Daniel

推荐答案

通过在变量声明前添加window.AppD来解决

Solved by adding window.AppD in front of the variable declaration.

Andrew Noyes在另一个问题中提供的解决方案:

Solution provided by Andrew Noyes in another question:

在线上onclick处理程序中可以做什么有任何限制?

这篇关于为什么这个bookmarklet JS代码放在onclick处理程序中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆