I'm making my own function for the first time $.fn.testing = function(){....}
;
But i'm having a problem that I'm not able to solve yet. The next scenario isn't smart, but It might happen, so that's the reason why I want to fix it so the user doesn't have to:
$('.target').testing("message" : "Hello!");
$('#test .target').testing("message" : "Hello world!");
The function will make the 'message' pop-up. So what the user wants here is that, for every .target
there has to be an pop-upbox with "Hello!" and if this .target
also has an id of #test
then it should pop-up: "Hello world!". But the problem is, that now the script will pop-up "Hello!" AND "Hello world!" when the .target#test
is triggered.
So what I want in my function is that the function sees if the function is already called on this object, and if it is it has to .unbind()
the previous function and then continues to add the function.
How can I achieve this? Hopefully my explanation is clear enough!
(The example above is a little bit simplified, so please don't comment on the use of it)
Help 开发者_如何学Cis appreciated!
Here is how I would do this:
var _myFunction = function() {
alert($(this).data("message"));
};
in plugin do something like this
jQuery.fn.testing = function(msg) {
this
.data("message", msg)
.unbind('click', _myFunction)
.bind('click', _myFunction);
};
EDIT: here is an example in jsfiddle
You could do:
$('.target#test').testing("message" : "Hello world!");
$('.target:not(#test)').testing("message" : "Hello!");
EDIT - do you mean something like this?
$('.target').testing(function(e){
if (this.id === 'event'){
alert('hello world');
}else{
alert('hello');
}
});
As far as I understood: For example you have a popup on target appended to target element and now the popup is a child to target, or may be you could have implemented otherwise. My point is to whenever a call to the function is made it will check if the popup is inserted into DOM. If it is first it would remove that popup and then insert a new one with new message.
I mean Like...
function() {
//if a pop is present
$('.popup').remove();
var msg = $(this).attr('title'); //for example
var popup = "html containin msg...";
$(this).append(popup);
}
Don't know if this is the right way to do it, but I figgured it out myself. It was very easy, just add $(this).unbind()
in the beginning of youre own function. It will remove all previously added functions and still continues to add the current one. I had tried it before but with an extra selector: $(this).unbind(".testing")
, that didn't work for some reason but now I have it working.
Thanks for youre answers and youre help! Really appreciate it!
Try this
var $this. msg;
$('.target').each(function(){
$this = $(this);
if((#this.attr("id) != "#test") || ($this.find("#test").length == 0))//here check for all the possible ids you want){
msg = "message" : "Hello world!";
}
else{
msg = "message" : "Hello!";
}
$this.testing(msg);
});
精彩评论