我目前不知道如何获取该类的值,例如我在下面发布的代码。如果我单击值为0的li类,我希望它执行A如果我单击值为1的li类,我希望它执行B
I'm using bootstrap and jquery/javascript.
Sorry if my code seems not tidy, this is my first post , i'll try to tidy it up in the next posts.
I've been doing inspect elements and it's showed me no error, but the variable X isn't getting it's value from li.
如果选择的值为0,这是我希望它执行A
$(".clDropdown").click(function() {
debugger ;var x = document.getElementsByClassName("clDropdown").selectedIndex;
if (x == 0) {
alert("DO A");
debugger ;
} else if (x == 1) {
alert("DO B");
debugger ;
}
});
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
More <span class="caret"></span>
</button>
<ul class="dropdown-menu">//if 0 do A
<li class="clDropdown" value="0"><a href="#">Edit</a></li>
<li class="clDropdown" value="1"><a href="#">Delete</a></li>
</ul>
</div>
I expect that if i click the li that value 0 it'll do A , and if i click the li that has value 1 it'll do B
答案 0 :(得分:1)
如果您想获得index
,可以使用$(this).index()
我更喜欢使用data
属性并使用$(this).data('value')
$(".clDropdown").click(function() {
debugger;
var x = $(this).data('value');
if (x == 0) {
alert("DO A");
debugger;
} else if (x == 1) {
alert("DO B");
debugger;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
More <span class="caret"></span>
</button>
<ul class="dropdown-menu">//if 0 do A
<li class="clDropdown" data-value="0"><a href="#">Edit</a></li>
<li class="clDropdown" data-value="1"><a href="#">Delete</a></li>
</ul>
</div>