为什么这不起作用如果我给它添加空格?

时间:2014-03-11 08:42:44

标签: javascript jquery

所以我正在制作一个博客平台的主题,我只有模板编辑访问权限(意味着我无法控制来自服务器的内容)。我想删除重复我想从博客中删除重复的图像post page.Here是代码

如果alt标签没有空格

,它工作正常
<p>Alt with Spaces.Works fine!</p>

http://jsfiddle.net/mixin/mB7mz/2/

如果alt包含空格,则不起作用 http://jsfiddle.net/mixin/G27fk/

这里有什么问题?

4 个答案:

答案 0 :(得分:1)

将alt属性的单引号更改为double

 try following 

function postHeaderImage(){
            headerImage = $('#post-header img').attr('alt');

            $('#post-content img').each(function() {
                postContentImage = $(this).attr('alt');

                if(postContentImage == headerImage){
                    $("#post-content img[alt='"+ postContentImage+"']").remove();
                }
            });
        }

答案 1 :(得分:0)

您的选择器指向不同的ID。

http://jsfiddle.net/G27fk/4/

试试这个:

$('#post-content img').each(function() {

答案 2 :(得分:0)

问题在于您删除重复图像的方式,有一种更优雅的方法。我将您的JSFiddle更新为一个工作示例:http://jsfiddle.net/mB7mz/3/

$(document).ready(function(){

    function postHeaderImage(){
        headerImage = $('#post-header img').attr('alt');
        $('#post-content img').each(function() {
            postContentImage = $(this).attr('alt');
            if(postContentImage == headerImage){
                $(this).remove();
            }
        });
    }

    postHeaderImage();

});

答案 3 :(得分:0)

有两个问题。

  • 第二个代码中使用的ID不匹配
  • 属性选择器区分大小写alt&amp;值<{li>中的Alt

所以

$(document).ready(function () {

    function postHeaderImage() {
        var headerImage = $('#header-image img').attr('alt');
        $('#post-content img[alt="' + headerImage + '"]').remove();
    }

    postHeaderImage();

});

演示:Fiddle


如果您想要不区分大小写的搜索,那么

$(document).ready(function () {
    function postHeaderImage() {
        var headerImage = $('#header-image img').attr('alt').toLowerCase();
        $('#post-content img[alt]').filter(function () {
            return $(this).attr('alt').toLowerCase() == headerImage;
        }).remove();
    }

    postHeaderImage();
});

演示:Fiddle