[英]how do i apply Onselect method to drop down menu in javascript
i am using twitter bootstrap to create a drop down menu, the menu contains 2 sub-menus as shown: 我正在使用twitter bootstrap创建一个下拉菜单,该菜单包含2个子菜单,如下所示:
<div class="Menu"">
<div class="btn-group">
<button type="button" id="someaction" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select Action
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a class="add">Add</a></li>
<li><a class="remove">Remove</a></li>
</ul>
</div>
</div>
Using JavaScript how do i add actions to each sub menus, so for example when i select Add it should alert me "Add" and when i click remove it should alert me "Remove".
使用JavaScript如何将操作添加到每个子菜单,例如,当我选择“添加”时,它会提醒我“添加”,而当我单击“删除”时,它会提醒我“删除”。 I think if loop will do a job for me, for example if (Add is selected do this else if Remove is selected do something else .. i would like to use this to perform different actions based on sub menus
我认为if循环会为我做一个工作,例如,如果(选择“添加”,则执行此操作;如果选择“删除”,则进行其他操作。
$(".dropdown-menu li a").click(function () {
});
The selector
that you are using is perfectly alright, But since you are adding a click
event to an anchor
tag, You can optionally use .preventDefault()
to prevent the page redirecting, 您使用的
selector
是完全可以的,但是由于您要向anchor
标记添加click
事件,因此可以选择使用.preventDefault()
来防止页面重定向,
Just try, 你试一试,
$(".dropdown-menu li a").click(function (e) {
e.preventDefault();
alert($(this).text());
});
Note: you have to use .text()
method to retrieve the text inside a tag. 注意:您必须使用
.text()
方法来检索标签内的文本。
You can refer to the fiddle http://jsfiddle.net/9GZQ2/ and can do what you want to do. 您可以参考小提琴http://jsfiddle.net/9GZQ2/并可以做您想做的事情。 All you need to do is to change the tasks inside the function for you it will be: alert($(this).text());
您需要做的就是为您更改函数内的任务,即是:alert($(this).text());
$(function(){
$("#ProducterType").change(function(){
alert($(this).text());
});
$("#Role").change(function(){
alert($(this).text());
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.