【问题标题】:How to call a Javascript function onselection of menuitem?如何调用 Javascript 函数 onselection of menuitem?
【发布时间】:2014-07-10 10:21:48
【问题描述】:

对于一个菜单项的onselect 事件(在选择菜单项时),我如何调用如下的 Javascript 函数 test(),如下面的代码?

我一直在处理按钮中的OnClick 事件,但我不知道菜单项的OnSelect 事件,如何调用菜单项的选择函数。

谁能建议我下面的代码如何工作并在选择名为 Log Report 的菜单项时调用我的函数 test() (code 1),如 代码2

<ul>
<li>Log Report</li>
</ul>

代码 1

<script>
function test() {
    window.open("www.google.com");
}
</script>

代码 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>

【问题讨论】:

    标签: javascript jquery jquery-events menuitem onselect


    【解决方案1】:

    不要为每个li创建一个函数,建议使用data属性

    <ul id="menu">
      <li>Database</li>
      <li>Log
        <ul>
          <li data-page="www.google.com">Log Report</li>
        </ul>
      </li>
    </ul>
    

    然后在函数中传入

    $('#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;
    }
    

    【讨论】:

      【解决方案2】:

      我想你在找这个

          $("#menu").on("click", "li", function(event){
            test();    
            console.log('clicked');
           });
      

      希望这会有所帮助... 更多信息 DEMO JSFiddle

      【讨论】:

        【解决方案3】:

        当你使用 jQuery UI Menu Widget,使用select event,当一个菜单项被选中时触发。

        $('#menu').menu({
            select: function (event, ui) {
                test();
            }
        });
        

        另一种方法是

        $("#menu").on("menuselect", function (event, ui) {
            test();
        });
        

        【讨论】:

          【解决方案4】:

          使用点击事件

            $("#menu li").click(function(){
                test();    
               });
          

          【讨论】:

            猜你喜欢
            • 2014-10-17
            • 2016-07-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-08-21
            • 2011-07-06
            • 1970-01-01
            • 2019-01-07
            相关资源
            最近更新 更多