简体   繁体   English

一键触发两次Onclick功能

[英]Onclick function fires Twice with one click

I have a foreach in the razor : 我的剃须刀上有一个foreach

<ul>
    @foreach (var node in Model)
    {
        var par = node.Id;
        <li onclick="GetSubMenu(this)" id="@node.Id">
            @node.Title
        </li>
    }
</ul>

in onclick i called method in the : 在onclick我在中调用方法:

function GetSubMenu(e) {
    debugger;
    $.ajax({
        type: "Get",
        url: "/Menu/GetSubMenu",
        data: { parentId: e.id },
        contentType: "application/json; charset=utf-8",
        dataType: "json",

    }).done(function (result) {
        $.each(result, function (index, val) {               
            $("#" + val.ParentId).append("<ul><li onclick='GetSubMenu(this)' id='" + val.Id + "'>" + val.Title + "</li></ul>");

        });
    });
}

and in controller i return the submenu of parent menu(which i click on it): 在控制器中,我返回父菜单的子菜单(我单击它):

   public JsonResult GetSubMenu(string parentId)
    {
        int id = int.Parse(parentId);
        return Json(db.PrmMenus.Where(x => x.ParentId == id), JsonRequestBehavior.AllowGet);
    }

the first time all thing was ok, and the sub menu will show properly, but in seccond time when i click on submenu, the onclick function call for submenu and the parent menu again, what is the problem? 第一次一切正常,并且子菜单将正确显示,但是在第二次单击子菜单时,onclick函数再次调用子菜单和父菜单,这是什么问题?

The problem is, when you click on the child element, It is calling the onclick event for the child element and parent element because child is contained inside the parent! 问题是,当您单击子元素时,它正在调用子元素和父元素的onclick事件,因为子包含在父元素中!

You can use jQuery stopPropogation method to stop bubbling the event. 您可以使用jQuery stopPropogation方法停止冒泡事件。 this method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. 此方法防止事件使DOM树冒泡,从而防止任何父处理程序收到该事件的通知。

Converting your code to unobtrusive javascript 将您的代码转换为简洁的JavaScript

<li class="menuItem" id="@node.Id">
     @node.Title
</li>

and listen to the click event on the items with "menuItem" class 并使用“ menuItem”类监听项目的click事件

$(function(){

   $(document).on("click",".menuItem",function(e){
       e.stopPropagation();

       var id=$(this).attr("id");
       ///Do your ajax call here
   });

});

Make sure you build the same sort of markup for child elements in your ajax method's done event (one with the same css class) 确保在ajax方法的done事件中为子元素构建相同类型的标记(一个标记具有相同的CSS类)

Here is a working jsfiddle 这是一个工作的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM