How can I call a Javascript function test()
as below for the onselect
event (upon selection of menu item) of a menu item as for my below code?
I have always worked on OnClick
event in button but I have no idea about OnSelect
events for the menuitems, how to call a function onselection of menuitem.
Can anyone suggest how can my code below work and call my function test()
(code 1) on selection of menu item named Log Report as in code-2?
<ul>
<li>Log Report</li>
</ul>
Code-1
<script>
function test() {
window.open("www.google.com");
}
</script>
Code-2
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test screen</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
<script>
$(function() {
$( "#menu" ).menu();
});
</script>
<style>
.ui-menu { width: 230px; }
</style>
</head>
<body>
<ul id="menu">
<li>Database</li>
<li>Log
<ul>
<li>Log Report</li>
</ul>
</li>
</html>
To not create a function for every li
, suggest the use of data
attribute
<ul id="menu">
<li>Database</li>
<li>Log
<ul>
<li data-page="www.google.com">Log Report</li>
</ul>
</li>
</ul>
Then pass it in the function
$('#menu li').click(function(){
test($(this).data('page'));// which will give "www.google.com" if clicked on the Log Report
}
function test(url){
window.open = url;
}