简体   繁体   English

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

[英]If li has less than 3 characters, hide?

I want to be able to hide list items that have less than 3 characters, how do I do this? 我希望能够隐藏少于3个字符的列表项,我该怎么做? What is wrong with my code below? 我的代码有什么问题?

I am a JavaScript/jQuery newbie. 我是一个JavaScript / jQuery新手。

jQuery().ready(function () {
    if (jQuery('ol li').length < 3) {
        jQuery(this).hide();
    };
});

Your code is saying 你的代码在说

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

What you want to use is filter 你想要使用的是过滤器

$('ol li').filter( function(){ return $(this).text().length<3; } ).hide();

EDIT - Based on your comment in my post: If it is a span tag that could have other data around it: 编辑 - 根据您在我的帖子中的评论:如果它是一个span标记,可能有其他数据:

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

Fiddle running the span example 小提琴运行跨度示例

You'll need to filter out the elements that have a content of less than 3 characters, and hide those : 您需要过滤掉内容少于3个字符的元素,并隐藏它们:

$(function() {
    $('ol li').filter(function() {
        return $(this).text().length < 3 ;
    }).hide();
});
$('ul li').each(function() {
    if ($(this).text().length < 3)
        $(this).hide();
});

Demo 演示

Try this: 尝试这个:

$('ol li').filter(function(){ return $(this).text().length < 3; }).hide();

Another alternative could be this: 另一种选择可能是这样的:

(Because you are evaluating elements not value characters in your question code snippet) (因为您正在评估问题代码段中的元素而不是值字符)

if($('ol li').length < 3){ $(this).hide(); };

我认为你需要得到你的DOM元素的.html() ,然后做.length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM