javascript conflict
why does some java开发者_StackOverflowscripts come in conflict with some other ones? I mean I had been using javascript code for image gallery and then tried to get the text watermark in jquery. Why is that after using the jquery, the gallery totally disappeared? there was no common ids that I used inthe two scripts. Any reason for that?
As Mathias has correctly pointed out, the most likely problem is that your other library is also using the $
symbol -- when you added jQuery to the page it overwrote the old $
variable with its own $
... and your first javascript library ceased to work. The solution is to call jQuery.noConflict() to restore the $
variable to the first library. You will still be able to use jQuery plugins -- you will just need to update example scripts that use $
to use jQuery
instead. Thus $("#my_content").css({color: "red"});
would become jQuery("#my_content").css({color: "red"});
Alternately, you can assign the jQuery object to another variable object in this manner:
$jq=jQuery.noConflict(); //From now on jQuery can be called with the $jq function
or you can use it within a closure:
(function($) {
// $ in here will map to jQuery
//outside of this code $ will map to your other library's $
})(jQuery.noConflict());
Try this one: http://api.jquery.com/jQuery.noConflict/
Sometimes people may use global variables in their packaged javascript. If you have two packages which use the same global variable, obviously there's going to be problems. To resolve it, what you could try is to create a closure around each different package's code. Without seeing the code, I'm not 100% that it would work, but here's an example:
// gallery.js
var textTitle = "Image gallery";
function getGalleryTitle() { return textTitle; }
//////////////
// watermark.js
var textTitle = "Watermark";
alert(getGalleryTitle()); // "Watermark" :(
Now with closures, created by using anonymous functions:
(function() {
var textTitle = "Image gallery";
function getGalleryTitle() {
return textTitle; // this will always be "Image gallery"
}
})();
(function() {
var textTitle = "Watermark"; // won't conflict with any other code.
})();
The downside here is that you can no longer access those variables and functions globally (eg, via inline event handlers).
精彩评论