检查页面中是否存在src
我有一个生成 img 标签的脚本,我想确保相同的 img 不会被制作两次。这是我尝试创建的脚本:
var included = 0;
var src = "";
jQuery.fn.checkCard = function() {
if ($("#L_S_Inner").find($('img').attr(src))){
included = 0;
} else {
included = 1;
}
}
但是它不起作用。不知道我在这里做错了什么...
它是这样构建的,这样我就可以检查我的 img 创建脚本中“包含”的变量。
编辑
添加了img创建脚本:
$('#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 + ''}));
}
});
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
Added 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 + ''}));
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有几个问题。首先,尽管您有解释,但我认为不需要全局变量。这是丑陋且危险的做法 - 它应该是函数的返回值,除非你有充分的理由不这样做。
其次,正如 @sosborn 所说,该函数没有输入参数 - src 要么是另一个全局变量(您尚未显示),要么代码无法工作。
接下来,在
find
内部应该有一个选择器,而不是 jQuery 对象,在attr
内部应该有一个属性名称(因此,一个字符串"src"< /code>),而不是一个值(大概
src
包含类似http://...
的内容)。另外,为什么要把它做成一个 jQuery 插件呢?
问题的字面解决方案,我会这样做:
更好的解决方案是通过手动跟踪来记住您创建的图像 - 更快。
更新:发布创建代码后,让我重写第二个解决方案:
顺便说一下,请注意我添加到内部变量中的
var
。声明你的变量,这对健康有益。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 insideattr
there should be an attribute name (thus, a string"src"
), not a value (presumablysrc
contains something likehttp://...
).Also, why make it into a jQuery plugin?
Literal solution of the problem, I'd do this way:
A better yet solution is to remember what images you create by tracking them manually - much faster.
UPDATE: With the creation code posted, let me rewrite the second solution:
By the way, notice the
var
s I added to your inner variables. Declare your variables, it's good for health.