我有一些PHP代码生成HTML,并且根据某些DIV中的某些条件,某些按钮可以使用jQuery动态创建(在文档加载之后)。可能包含按钮的DIV具有初始css隐藏状态。
虽然隐藏了包含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?
答案 0 :(得分: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
答案 1 :(得分:0)
首先迭代每个重复的div,然后在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>