jquery plugin default option modification once applied
Take the following example plugin:
(function($) {
$.fn.alertOnClick = function(text) {
return this.each(function(){
$(this).click(alert(text));
});
}
})(jQuery);
that I might use like this:
$('p').alertOnClick("this is a silly plugin");
How do I modify the plugin code to support doing the following:
$('p').alertOnClick("this is a silly plugin");
$('p#someSpecificP').setAlertText("different alert text");
this would have the effect that all p
's when clicked should display "this is a silly plugin"
except the p
with id "someSpecificP"
which would display "different alert text"
.
This example is obviously not my real code, but serves as an analogy. I have a plugin applied to m开发者_C百科any elements with defaults. During the life of the page, I may want to change some of the default settings for individual elements with the plugin applied to them, but not all.
Thanks
solved it with data()
, not sure if thats the best approach though...
(function($) {
$.fn.alertOnClick = function(text) {
return this.each(function(){
$(this).data('alertText', text).click(function(){
alert($(this).data('alertText'));
});
});
}
$.fn.setAlertText = function(text) {
return this.data('alertText', text);
}
})(jQuery);
Why not do something like this:
$("p").not("#p1").alertOnClick("Hello");
$("#p1").alertOnClick("Bye");
Calling alertOnClick again on an element works. Just remember to unbind all click events and then apply the new one.
<p>test 1</p>
<p>test 2</p>
<p id="s1">test 3</p>
<p>test 4</p>
<script type="text/javascript">
(function($) {
$.fn.alertOnClick = function(text) {
return this.each(function(){
$(this).unbind('click');
$(this).bind('click', {'t' : text}, function(e){
alert(e.data.t);
});
});
}
})(jQuery);
$('p').alertOnClick('common alert');
$('p#s1').alertOnClick('unique alert');
</script>
This works fine for me. I've just unbind previuosly binded events from target elements.
I haven't tried it out, but you should be able to define a member function, something like that:
(function($) {
$.fn.alertOnClick = function(text) {
setAlertText: function(newText) {
$(this).click(alert(newText));
}
return this.each(function(){
$(this).click(alert(text));
});
}
})(jQuery);
精彩评论