简体   繁体   English

当放入onclick处理程序时,为什么此小书签JS代码不起作用?

[英]Why does this bookmarklet JS code not work when put in an onclick handler?

I have a pretty typical bookmarklet code that's working perfectly for me in all browsers. 我有一个非常典型的bookmarklet代码,它在所有浏览器中都非常适合我。 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). 但是,当我将这段代码放入HTML的元素onClick处理程序中时,它在IE(6、7或8)中不起作用。

This is the code: 这是代码:

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');})();

And that works perfectly. 而且效果很好。 I've taken out the javascript: prefix, and put it into an element's onClick: 我已取出javascript:前缀,并将其放入元素的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');})();" />

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... 而且效果也很好,除了在IE中外,bk.js(注入的脚本)中的代码抱怨未定义变量AppD ...

Any ideas why this is happening? 任何想法为什么会这样?
Is there any limitation to the code one can put in an onClick handler? 一个人可以放在onClick处理程序中的代码有任何限制吗?

Thanks! 谢谢! Daniel 丹尼尔

Solved by adding window.AppD in front of the variable declaration. 通过在变量声明之前添加window.AppD来解决。

Solution provided by Andrew Noyes in another question: Andrew Noyes在另一个问题中提供的解决方案:

Are there any limitations to what can be done in an inline onclick handler? 内联onclick处理程序中可以执行的操作是否有任何限制?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM