Uncaught TypeError: Object #<HTMLDivElement> has no method 'addPanel'

给你一囗甜甜゛ 提交于 2020-01-10 05:37:06

问题


I am trying to implement an almost cross-browser bookmark functionality and found this on SO: How do I add an "Add to Favorites" button or link on my website?

Now, I am using @PHPst's answer..

<script type="text/javascript">
$(function() {
    $("#bookmarkme").click(function() {
        if (window.sidebar) { // Mozilla Firefox Bookmark
            window.sidebar.addPanel(location.href,document.title,"");
        } else if( /*@cc_on!@*/false) { // IE Favorite
            window.external.AddFavorite(location.href,document.title); 
        } else if(window.opera && window.print) { // Opera Hotlist
            this.title=document.title;
            return true;
        } else { // webkit - safari/chrome
            alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
        }
    });
});
</script>

it works on a plain webpage.. as demonstrated here: http://jsfiddle.net/GXas4/

but when i use it inside a wordpress template, in chrome i get a js error like this:

Uncaught TypeError: Object #<HTMLDivElement> has no method 'addPanel' 

it does not return an error on the console of firefox but does not do anything too.

a lot of posts on SO have questions starting like this ('Uncaught TypeError: Object # has no method') but nothing seems to point me to the right direction.

Has anyone have an idea why this is happening?


回答1:


It's possible that the WordPress theme you are using has an element with id=sidebar.

Unless a global variable with the same name has been explicitly defined, a global variable will be created for each element that has an id.

So, the first test is unreliable. For example, evaluating window.sidebar on the stackoverflow page will be true even in Chrome, because the website uses an element with such an id.




回答2:


You should use wp_enqueue_script (Documentation)

Your dependencies may not being called before that script. If you enqueue the script you can make the dependencies load first using

wp_enqueue_script( $handle, $path to file, array( jquery ));`

Since I placed jQuery in the array it will now load jQuery before the script.




回答3:


addPanel was removed from Firefox since v. 23. But you can use markup instead:

<a href="http://stackoverflow.com" title="Stack Overflow" rel="sidebar">Bookmark me</a>


来源:https://stackoverflow.com/questions/17747578/uncaught-typeerror-object-htmldivelement-has-no-method-addpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!