Jquery - select all anchor tags with display:block

2019-08-13 07:57发布

I can't get my head around how to do this?

Given a page full of anchor tags, I only want to select those elements with the CSS property display:block.

I think I can do it with a jQuery loop (warning pseudo code!)

var myarray;
$('a').each(function(arg1, arg2) { 
    if ($(arg2).css('display')=='block')
    myarray.push(arg2);
}

But isn't there a simpler way?

6条回答
Deceive 欺骗
2楼-- · 2019-08-13 08:22

Or more simple:

$("a:visible")
查看更多
手持菜刀,她持情操
3楼-- · 2019-08-13 08:25

You can use filter with a function as the parameter.

$('a').filter(function (index) {
                  return $(this).css("display") === "block";
              })
查看更多
贪生不怕死
4楼-- · 2019-08-13 08:27

If you want to have it as a jquery tool (if you use it very often). You can extend the ":" selector by adding the following code to your project:

$.extend($.expr[':'], {
    "block": function(a, i, m) {
        return $(a).css("display") == "block";
    }
});

and then you can select all block anchors by saying this:

var res = $("a:block");

see example here: http://jsfiddle.net/zFatd/7/

[NOTE] as you can see in the example if you use ":block" on a naturally block element (i.e. div) it will still returns true. (in other words "div:block" is true unless you specifically give it something other than block)

查看更多
在下西门庆
5楼-- · 2019-08-13 08:31

Another way to do this would be to use jQuery's attribute selector:

$("a[style$='display: block;']")
查看更多
欢心
6楼-- · 2019-08-13 08:31

I would assume that the display property is set by having a certain class or other property. This should make the selection simpler by using that attribute. Also, if ther other anchors are hidden, you can display the visible ones using the $('a:visible') selector.

查看更多
爷的心禁止访问
7楼-- · 2019-08-13 08:33

//hide all items with css display as block (slow):

$('*').filter(function(index) {
  return $(this).css('display')=='block';
}).hide();
查看更多
登录 后发表回答