检查页面上是否存在src

C_K*_*C_K 1 jquery find attr

我有一个生成img标签的脚本,我想确保同一个img没有生成两次.这是我试图创建的脚本:

var included = 0;
var src = "";

jQuery.fn.checkCard = function() {
    if ($("#L_S_Inner").find($('img').attr(src))){
        included = 0;
    } else {
        included = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.不知道我在这里做错了什么......

它以这种方式构图,以便我可以在我的img创建脚本中检查变量'included'.

编辑

添加了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 + ''}));
    }
});
Run Code Online (Sandbox Code Playgroud)

Ama*_*dan 5

这里有几个问题.首先,尽管你的解释,我认为不需要全局变量.这是丑陋和危险的做法 - 它应该是函数的返回值,除非你有充分的理由不这样做.

其次,正如@sosborn所说,该函数没有输入参数 - src要么是另一个全局(你没有显示),要么代码无法工作.

接下来,里面find应该有一个选择器,而不是一个jQuery对象,里面attr应该有一个属性名称(因此,一个字符串"src"),而不是一个值(可能src包含类似的东西http://...).

另外,为什么要把它变成一个jQuery插件?

问题的直接解决方案,我这样做:

var checkCard = function(src) {
    return !!($('#L_S_Inner img[src="' + src + '"]').length);
}
Run Code Online (Sandbox Code Playgroud)

更好的解决方案是通过手动跟踪它们来记住您创建的图像 - 速度更快.

var included = [];
// ...
// when you make an image
included[src] = true;
// ...
// when you want to know if it is there
if (included.hasOwnProperty(src)) // ...
Run Code Online (Sandbox Code Playgroud)

更新:发布创建代码后,让我重写第二个解决方案:

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

顺便说一句,请注意var我添加到内部变量中的s.声明你的变量,它对健康有好处.