2012-03-29 70 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