2012-03-29 72 views
2

实施例:我想得到div的ID是从最后一个显示块到第一个div?

<div id="parent"> 
    <div id="1" style="display:block"></div> 
    <div id="23" style="display:block"></div> 
    <div id="42" style="display:block"></div> 
    <div id="32" style="display:none"></div> 
</div> 

根据该示例我想要得到的div ID的id = 42处于第二最后位置。我想找到显示块的div,并从最后找到。

+0

你需要显示一些代码,我猜... – 2012-03-29 05:59:21

回答

1

你的情况u可以使用:

var last_id = $('div:visible').last().attr('id'); 
1

您可以通过这种方式找到它

$("#parent div[style*='display:block']'").last().attr("id") 

见的jsfiddle http://jsfiddle.net/UhzRU/4/

如果你想找到所有可见的div(不仅显示:块),这将是更好地使用这种

$("#parent div:visible").last().attr("id") 
+0

Downvoter,请告诉我你downvote的原因。 – 2012-03-29 06:26:03

+0

在':'和'block'之间加一个空格,你会得到'undefined'。这可能是错误的。 – Joseph 2012-03-29 06:35:18

+0

是的,:可见更好。 – 2012-03-29 06:43:39

0

这适用于您的测试HTML

x = $('#parent div').filter(function() {if ($(this).css('display') == 'block') return $('this')}); 
x = x[x.length - 1]; 

x现在是display: block;

1

我想获得ID为DIV是显示块从后到前格的最后一个div?

here's a demo

$(function(){ 

    var ids = []; 

    $('#parent > *').filter(function(){ 
     return this.style.display === 'block'; 
    }).each(function(){ 
     ids.unshift(this.id); 
    }); 

    console.log(ids) 
});​ 
+0

你不觉得这是非常长的解决方案吗? – 2012-03-29 06:11:39

+0

@ChuckNorris nope。唯一重要的是过滤器,get和reverse。 – Joseph 2012-03-29 06:22:47

+0

是的,有更多的行动,当这可以用更简单的方式完成:) – 2012-03-29 06:24:53

0

使用第n-最后子函数:这里是一个链接

http://benalman.com/projects/jquery-misc-plugins/#nth-last-child

(function($){ 
    '$:nomunge'; // Used by YUI compressor. 

    $.fn.queueFn = function(fn) { 
    var i, 
     that, 
     args = Array.prototype.slice.call(arguments, 1); 

    if (typeof fn === 'boolean') { 
     if (fn) { 
     that = this; 
     i = this.length; 
     } 
     fn = args.shift(); 
    } 

    fn = $.isFunction(fn) ? fn : $.fn[ fn ]; 

    return this.queue(function(){ 
     !--i && fn.apply(that || this, args); 
     $.dequeue(this); 
    }); 
    }; 

})(jQuery); 

var elems = $('#parent div:nth-last-child(2)'); 
alert(elems.attr('id')); 
0

我希望这个作品

var reqId = "" 
var child = $("#parent").children().last(); 
while($(child).css("display")!="block" && $(child).length!=0){ 
    child = $(child).prev(); 
} 
if($(child).length!=0){ 
    reqId = $(child).attr("id"); 
} 
+0

thk to all for reply – pargan 2012-03-29 08:02:46