我有多级按钮,我选择1级按钮之一,我想在下一级显示按钮。
现在,我希望获得使用JavaScript代码选择的按钮值。以下是我的代码。我带来了显示多级按钮的代码:
<script type="text/javascript">
var menuArray = ['0'];
$(function () {
$('.showButton').click(function () {
//get target div to show
var targetID = $(this).attr('target');
//hide all divs
$('.targetDiv').hide();
//show all menu items in chain
var found = false;
//get containing div target number
var current = $(this).parent().attr('id').toString().charAt(3);
var length = menuArray.length;
//remove elements of array lower than clicked button
for(var i=0; i<length; i++) {
//check if next menu item is a button just pressed and never delete root menu (elem == 0)
if(menuArray[0] == current || menuArray[0] == 0) {
$(this).addClass('selected').siblings().removeClass('selected');
found = true;
}
//hide div if no longer in menu structure and remove from menuArray[0]
if(!found) {
$('#div' + menuArray[0]).hide();
menuArray.shift();
}
};
//add new target to beginning of array
menuArray.unshift(targetID);
//show each element in the menu structure
menuArray.forEach(function(elem, index) {
if(index != 0) {
$('#div' + elem).show();
}
});
//get div of target to show sliding effect
var targetDiv = $('#div' + menuArray[0]);
//show the div as the last element on the page
targetDiv.insertAfter('#div' + menuArray[1]);
//slide out last div
targetDiv.show('slide');
});
});
</script>
<div id="div0" class="buttons">
<div class="showButton" target="1">A_Level1</div>
<div class="showButton" target="1">B_Level1</div>
<div class="showButton" target="1">C_Level1</div>
</div>
<!-- div1 Branch -->
<div id="div1" class="targetDiv">
<div class="showButton" target="6">A_Level2</div>
<div class="showButton" target="6">B_Level2</div>
<div class="showButton" target="6">C_Level2</div>
</div>
<div id="div6" class="targetDiv">
<div class="showButton" target="7">A_Level3</div>
<div class="showButton" target="8">B_Level3</div>
<div class="showButton" target="9">C_Level3</div>
</div>
我该怎么办?
答案 0 :(得分:1)
在您的匿名函数内$('.showButton').click(function () {
,您可以使用$(this).text();
(或$(this).html();
访问该值,如果您需要任何html元素)。
使用此方法参见以下示例::
$('.showButton').click(function(){
$('#log').val($(this).text());
});
&#13;
.showButton{
cursor:pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div0" class="buttons">
<div class="showButton" target="1">A_Level1</div>
<div class="showButton" target="1">B_Level1</div>
<div class="showButton" target="1">C_Level1</div>
</div>
<!-- div1 Branch -->
<div id="div1" class="targetDiv">
<div class="showButton" target="6">A_Level2</div>
<div class="showButton" target="6">B_Level2</div>
<div class="showButton" target="6">C_Level2</div>
</div>
<div id="div6" class="targetDiv">
<div class="showButton" target="7">A_Level3</div>
<div class="showButton" target="8">B_Level3</div>
<div class="showButton" target="9">C_Level3</div>
</div>
<hr>
<textarea id='log'></textarea>
&#13;