如果li少于3个字符,请隐藏?

Aar*_*wer 6 javascript jquery dom

我希望能够隐藏少于3个字符的列表项,我该怎么做?我的代码有什么问题?

我是一个JavaScript/jQuery新手.

jQuery().ready(function () {
    if (jQuery('ol li').length < 3) {
        jQuery(this).hide();
    };
});
Run Code Online (Sandbox Code Playgroud)

epa*_*llo 12

你的代码在说

if (jQuery('ol li').length < 3) {  //If I have less than 3 li elements
    jQuery(this).hide();   //hide the window object
};
Run Code Online (Sandbox Code Playgroud)

你想要使用的是过滤器

$('ol li').filter( function(){ return $(this).text().length<3; } ).hide();
Run Code Online (Sandbox Code Playgroud)

编辑 - 根据您在我的帖子中的评论:如果它是一个span标记,可能有其他数据:

$('ol li span').filter( function(){ return $(this).text().length<3; } ).parent().hide()
Run Code Online (Sandbox Code Playgroud)

小提琴运行跨度示例


ade*_*neo 9

您需要过滤掉内容少于3个字符的元素,并隐藏它们:

$(function() {
    $('ol li').filter(function() {
        return $(this).text().length < 3 ;
    }).hide();
});
Run Code Online (Sandbox Code Playgroud)


Nik*_*vić 5

$('ul li').each(function() {
    if ($(this).text().length < 3)
        $(this).hide();
});
Run Code Online (Sandbox Code Playgroud)

演示