【问题标题】:How to point to the correct element with jQuery selector if multiple ones exist?如果存在多个元素,如何使用 jQuery 选择器指向正确的元素?
【发布时间】:2016-06-22 19:04:52
【问题描述】:

我在使用 jQuery 选择器选择 html 中的元素时遇到了困难。我正在使用复选框和视频标签创建分类过滤器。我试图弄清楚如何为每个基于视频标签显示/隐藏的视频缩略图元素以及复选框是否被选中具有唯一标识符。我有一个函数,它基本上从另一个函数中获取视频标签,该函数循环遍历每个视频并提取其标签数组值,如下所示:

// print the results
        function(data)
        {
            var output;

            $.each(data.items, 
                function(i, item) 
                {
                    var vidTitle = item.snippet.title; // video title
                    var vidDesc = item.snippet.description; // video description
                    var videoId = item.snippet.resourceId.videoId; // video id
                    var vidThumbUrl = item.snippet.thumbnails.default.url; // video thumbnail url
                    getVideoDuration(videoId).done(function(duration, view/*, tags*/)
                    {
                        vidDuration = duration;

                        viewCount = view;

                        //vidTags = tags;


                        // check if video tags is empty or undefined 
                        if(typeof videoTags === 'undefined' || videoTags == "" || videoTags === null)
                        {
                            videoTags = "No tags have been defined for this video.";
                        }


                        // check input categories
                        validateCategory(videoTags);


                        console.log("id: " + videoId + " duration: " + convert_time(vidDuration) + " viewCount: " + viewCount + ' videoTags: ' + videoTags); // return value in console
                        //console.log(JSON.stringify(item));
                        console.log("<br>");


                        output = '<li><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + videoId + '\"></iframe></li><div id="title">' + vidTitle + '</div><div id="desc">' + vidDesc + '</div><div id="duration">Length: ' + convert_time(vidDuration) + '</div><div id="stats">View Count: ' + viewCount + '</div><div id="tags">Tags: ' + videoTags + '</div>';

                        // if video title is longer than 25 characters, insert the three-dotted ellipse
                        if(vidTitle.length > 25)
                        {
                            var strNewVidTitle = vidTitle.substr(0, 25) + "...";
                            vidTitle = strNewVidTitle;
                        }
                        var vidThumbnail = '<div class="video-thumbnail"><a target="_blank" href="https://www.youtube.com/watch?v=' + videoId + '"><div class="video-overlay"><img src="imgs/video-play-button.png"/></div><img id="thumb" src="' + vidThumbUrl + '" alt="No Image Available." style="width:204px;height:128px"/></a><p><a target="_blank" href="https://www.youtube.com/watch?v=' + videoId + '">' + vidTitle + '</a><br/>' + convert_time(vidDuration) + ' / Views: ' + viewCount + '</p></div>';


                        // append results
                        $('#results').append(output);
                        $('#thumb').append(vidThumbnail);


                    }); // end of getVideoDuration(videoId).done
                }
            ); // end of getViewCount(videoId).done
        }         

现在,当复选框设置为选中时,它将检查input属性value="reading",如果它与标签匹配,则将.video-thumbnail类div属性设置为rel="reading"以唯一标识和分类每个视频.这是我到目前为止所尝试的:

// show/hide categorized videos
function validateCategory(videoTags) // TODO: add videoId to make an unique identifier for said video thumbnail.
{
    // check if input category is or isn't checked and omit videos not matching checked categories
    if($('input[value="reading"]').is(':checked'))
    {
        console.log('%c reading: ' + ".is(':checked'):", 'color:blue;'); // check if 'pregnancy' is checked
        for(i = 0; i < videoTags.length; i++)
        {
            if(videoTags[i] === "reading".trim().toLowerCase())
            {
                $('.video-thumbnail', this).css({visibility:'visible'});
                $('.video-thumbnail', this).show();
                $('.video-thumbnail', this).attr('rel','reading'); // set rel attribute according to tag name as a unique identifier
                $('.video-thumbnail', this).css({backgroundColor:'red'});
            }
            else
            {
                $('.video-thumbnail', this).css({visibility:'hidden'});
                $('.video-thumbnail', this).hide();
            }
        }
    }
    else
    {
        $('.video-thumbnail', this).css({visibility:'hidden'});
        $('.video-thumbnail', this).hide();
    }
}

HTML:

<div id="container">
    <h1>Youtube Videos</h1>
    <ul id="results"></ul>
    <hr/>
    <h1>Thumbnails</h1>
    <div id="thumb"></div>
    <div id="category-list" class="getFixed">
        <h1>Categories</h1>
        <input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading<br/>
        <input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
        <input class="categories" type="checkbox" name="filter" value="Science" checked>Science
    </div>
</div>

validateCategory(...) 函数将成功循环,但它不会引用 jQuery 选择器来使用this 视频缩略图类在选中/取消选中时显示/隐藏类别中的某些视频,就像类别过滤器一样。我什至做了背景颜色和可见性,但没有任何效果。我正在试图弄清楚如何将两者联系在一起。

【问题讨论】:

    标签: javascript jquery html jquery-selectors youtube-api


    【解决方案1】:

    看起来this 指的是您的validateCategory() 函数中的window 对象。 window 对象无法直接访问 dom,因此您需要使用 this.document 或仅使用 document。但是,在这种情况下,我认为您不想参考整个文档。这样做会在每次迭代中对.video-thumbnail 类的每个成员进行更改。我认为您想在为每个条目构建 vidThumbnail div 之后调用此函数,并将此 div 作为参数传递:

        function(data)
        {
            var output;
    
            $.each(data.items, 
                function(i, item) 
                {
                    var vidTitle = item.snippet.title; // video title
                    var vidDesc = item.snippet.description; // video description
                    var videoId = item.snippet.resourceId.videoId; // video id
                    var vidThumbUrl = item.snippet.thumbnails.default.url; // video thumbnail url
                    getVideoDuration(videoId).done(function(duration, view/*, tags*/)
                    {
                        vidDuration = duration;
    
                        viewCount = view;
    
                        //vidTags = tags;
    
    
                        // check if video tags is empty or undefined 
                        if(typeof videoTags === 'undefined' || videoTags == "" || videoTags === null)
                        {
                            videoTags = "No tags have been defined for this video.";
                        }
    
                        console.log("id: " + videoId + " duration: " + convert_time(vidDuration) + " viewCount: " + viewCount + ' videoTags: ' + videoTags); // return value in console
                        //console.log(JSON.stringify(item));
                        console.log("<br>");
    
    
                        output = '<li><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + videoId + '\"></iframe></li><div id="title">' + vidTitle + '</div><div id="desc">' + vidDesc + '</div><div id="duration">Length: ' + convert_time(vidDuration) + '</div><div id="stats">View Count: ' + viewCount + '</div><div id="tags">Tags: ' + videoTags + '</div>';
    
                        // if video title is longer than 25 characters, insert the three-dotted ellipse
                        if(vidTitle.length > 25)
                        {
                            var strNewVidTitle = vidTitle.substr(0, 25) + "...";
                            vidTitle = strNewVidTitle;
                        }
                        var vidThumbnail = '<div class="video-thumbnail"><a target="_blank" href="https://www.youtube.com/watch?v=' + videoId + '"><div class="video-overlay"><img src="imgs/video-play-button.png"/></div><img id="thumb" src="' + vidThumbUrl + '" alt="No Image Available." style="width:204px;height:128px"/></a><p><a target="_blank" href="https://www.youtube.com/watch?v=' + videoId + '">' + vidTitle + '</a><br/>' + convert_time(vidDuration) + ' / Views: ' + viewCount + '</p></div>';
    
                        // check input categories
                        validateCategory(videoTags, vidThumbnail);
    
                        // append results
                        $('#results').append(output);
                        $('#thumb').append(vidThumbnail);
    
    
                    }); // end of getVideoDuration(videoId).done
                }
            ); // end of getViewCount(videoId).done
        }
    
    
    function validateCategory(videoTags, vidThumbnail) // TODO: add videoId to make an unique identifier for said video thumbnail.
    {
        // check if input category is or isn't checked and omit videos not matching checked categories
        if($('input[value="reading"]').is(':checked'))
        {
            console.log('%c reading: ' + ".is(':checked'):", 'color:blue;'); // check if 'pregnancy' is checked
            for(i = 0; i < videoTags.length; i++)
            {
                if(videoTags[i] === "reading".trim().toLowerCase())
                {
                    $('.video-thumbnail', vidThumbnail).css({visibility:'visible'});
                    $('.video-thumbnail', vidThumbnail).show();
                    $('.video-thumbnail', vidThumbnail).attr('rel','reading'); // set rel attribute according to tag name as a unique identifier
                    $('.video-thumbnail', vidThumbnail).css({backgroundColor:'red'});
                }
                else
                {
                    $('.video-thumbnail', vidThumbnail).css({visibility:'hidden'});
                    $('.video-thumbnail', vidThumbnail).hide();
                }
            }
        }
        else
        {
            $('.video-thumbnail', vidThumbnail).css({visibility:'hidden'});
            $('.video-thumbnail', vidThumbnail).hide();
        }
    }  
    

    【讨论】:

    • 我试过这个,但没有用。结果还是一样。
    • 你看到了什么?根据 videoTags 列表中标签的顺序,一旦发现“正在读取”,您应该打破 for 循环以避免再次隐藏元素。
    • 即使在if(videoTags[i] === "Reading".trim().toLowerCase()){} 语句中使用break;,我也没有看到任何变化。
    猜你喜欢
    • 2012-04-12
    • 1970-01-01
    • 2010-12-17
    • 2016-08-06
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2011-07-06
    相关资源
    最近更新 更多