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

标签 javascript jquery dom

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

我是 JavaScript/jQuery 新手。

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

最佳答案

你的代码在说

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

你要用的是过滤器

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

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

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

Fiddle running the span example

关于javascript - 如果 li 少于 3 个字符,隐藏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11977388/

相关文章:

javascript - 使用 window.opener 检查父窗口在 IE 中不起作用

Javascript - 在加载另一个函数之后*运行函数?

html - Angular 7.1.4 HTML 避免复制粘贴重组

javascript - 使用 jquery-pjax 时如何强制一个链接进行整页加载

javascript - 在类中声明方法与在 JavaScript 中使用类原型(prototype)之间的区别

javascript - Chirpy 和 ASP.NET 4

php - 从 javascript 获取变量到 php

jquery - 我可以通过 jQuery 在一组同级中选择多个 'first-of-type' 吗?

node.js 在 POST 请求上刷新 DOM

javascript - 使用纯JS仅对某个类的一个div调用函数