Check if src exists on the page
I have a script that generates img tags, and i want to make sure the same img isn't being made twice. This is the script i tried to create:
var included = 0;
var src = "";
jQuery.fn.checkCard = function() {
if ($("#L_S_Inner").find($('img').attr(src))){
included = 0;
} else {
included = 1;
}
}
However it doesn't work. Not sure what i'm doing wrong here...
It's framed this way so that i can just check the variable 'included' in my img creation script.
EDIT
Adde开发者_JAVA技巧d the img creation script:
$('#Results a').live('dblclick', function() {
src = $(this).attr('href');
getC = $(this).attr('class');
checkCard();
if (!(checkCard)) {
$(this).parent().append($('<img />', {'src': src, 'class': 'DCT ' + getC + ''}));
}
});
Several problems here. First off, despite your explanation, I don't see the need for the global variable. It's ugly and dangerous practice - it should be the return value of the function, unless you have damned good reasons not to do it that way.
Second, the as @sosborn says, the function does not have an input parameter - the src
is either another global (that you haven't shown), or the code just can't work.
Next, inside find
there should be a selector, not a jQuery object, and inside attr
there should be an attribute name (thus, a string "src"
), not a value (presumably src
contains something like http://...
).
Also, why make it into a jQuery plugin?
Literal solution of the problem, I'd do this way:
var checkCard = function(src) {
return !!($('#L_S_Inner img[src="' + src + '"]').length);
}
A better yet solution is to remember what images you create by tracking them manually - much faster.
var included = [];
// ...
// when you make an image
included[src] = true;
// ...
// when you want to know if it is there
if (included.hasOwnProperty(src)) // ...
UPDATE: With the creation code posted, let me rewrite the second solution:
var included = [];
$('#Results a').live('dblclick', function() {
var src = $(this).attr('href');
var getC = $(this).attr('class');
if (!included.hasOwnProperty(src)) {
$(this).parent().append($('<img />', {'src': src, 'class': 'DCT ' + getC + ''}));
included[src] = true;
}
});
By the way, notice the var
s I added to your inner variables. Declare your variables, it's good for health.
精彩评论