2016-08-20 85 views
0

我有一些PHP代碼生成HTML和取決於某些DIV中的某些條件可能使用jQuery動態創建一些按鈕(文檔加載後)。可能包含按鈕的DIV有一個初始的css隱藏狀態。嵌套和(初始)隱藏的DIV中的jQuery計數嵌套按鈕

雖然包含div隱藏我需要:

  • 算多少按鈕有

  • 如果只有一個按鈕,返回按鈕的ID

HTML

<div id="row-buttons"> 
    <div> <!-- dynamically generated unknown id --> 
     <div id="classes-buttons-placeholder" style="display: none;"> 
      <!-- a DIV that may contain x buttons dynamically generated --> 
     </div> 
     <div style="clear:both"></div> 
     <div id="subjects-buttons-placeholder" style="display: none;"> 
      <div> 
       <!-- another DIV that may contain x buttons dynamically generated --> 
       <button id="Music" class="subjects-button"> Music</button> 
      </div> 
     </div> 
    </div> 
</div> 

在上面的例子中,我如何驗證是否只有一個按鈕,並在這種情況下返回ID?

回答

1

試試這個代碼

$(function(){ 
    $("div[id*='-buttons-placeholder']:hidden").each(function(){ 
    var buttons = $(this).find("button"); 
    if(buttons.length == 1) { 
     alert("Button inside " + $(this).attr("id") + ": " + buttons.attr("id")); 
    } 
    }); 
}); 

給出像Button inside subjects-buttons-placeholder: Music

的jsfiddle輸出:https://jsfiddle.net/vnathalye/bk4wbp6u/

+0

我看到,小提琴完美的作品,但在我的來源是行不通的。難道這是由於按鈕是動態創建的嗎?我記得有些函數在動態創建的對象上不起作用... – Riccardo

+0

我在創建按鈕之前測試的錯誤;-)工作!!!謝謝 – Riccardo

0

在每次重複格首先itertate,然後在DIV查找按鈕,返回ID

$('.master-divs').each(function(){ 
 
    
 
    b = $(this).find('button'); 
 
    if(b.length>0){ 
 
    button_id= b.attr('id'); 
 
    alert(button_id); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="row-buttons"> 
 
    <div> <!-- dynamically generated unknown id --> 
 
     <div id="classes-buttons-placeholder" class="master-divs" style="display: none;"> 
 
      <!-- a DIV that may contain x buttons dynamically generated --> 
 
     </div> 
 
     <div style="clear:both"></div> 
 
     <div id="subjects-buttons-placeholder" class="master-divs" style="display: none;"> 
 
      <div> 
 
       <!-- another DIV that may contain x buttons dynamically generated --> 
 
       <button id="Music" class="subjects-button"> Music</button> 
 
      </div> 
 
     </div> 
 
    </div> 
 
</div>

+0

也感謝您的解決方案! – Riccardo