简体   繁体   中英

Why must I define a variable outside a javascript function definition? (jQuery / #anchor question)

I am writing a jQuery function that relies on knowing the current #anchor of the page. I am using the jQuery URL Parser plugin to get the anchor.

 $.fn.vtabs = function() {
   alert("Your anchor is "+$.url.attr('anchor'));
 }

This code gives me the anchor "#nav" endlessly (I use #nav in some of the my links). I can type in "#newanchor" into the browser bar endless times, and click url's to this page that use different anchors, but always this code gives me "#nav".

I fixed my problem by changing the code to:

 var current_anchor = $.url.attr('anchor');
 $.fn.vtabs = function() {
   alert("Your anchor is "+current_anchor);
 }

Now it always gives me the correct anchor. But I don't know why, and it appears messy to have that variable defined outside of the function.

Looks like there might be some caching going on with that plugin. Why not skip the plugin and just use window.location.hash to get the anchor?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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