简体   繁体   English

单击带有 jQuery 的 div 内的链接时隐藏 div

[英]Hide div when clicking on link inside div with jQuery

on my website I have a mobile menu.在我的网站上,我有一个移动菜单。 When I click a link a link in the menu the menu doesn't disappear.当我单击菜单中的链接时,菜单不会消失。 From reading other posts I have a quite good idea what I have to do.通过阅读其他帖子,我非常清楚我必须做什么。 But I don't get the code working, because I am completely new to javascript and probably just do something wrong.但我没有让代码工作,因为我对 javascript 完全陌生,可能只是做错了什么。

The div I want to hide when clicking a link (in this same div) is defined with a class mobilemenuitems单击链接时要隐藏的 div(在同一个 div 中)是用 class mobilemenuitems 定义的

As I already mentioned the links are within this div.正如我已经提到的,链接在这个 div 中。

unfortunately I cannot add a class or an id to the links because I only have frontend access.不幸的是,我无法在链接中添加 class 或 id,因为我只有前端访问权限。

The website is here.网站在这里。 https://test.vereinonline.org/HTC_Uhlenhorst/?module= *Tennis Please note that the menu button only appears on mobile devices (width < 1000px) https://test.vereinonline.org/HTC_Uhlenhorst/?module= *网球 请注意菜单按钮仅出现在移动设备上(宽度 < 1000px)

In this jsfiddle the Problem is scaled down to the root.在这个 jsfiddle 中,问题被缩小到根。 http://jsfiddle.net/TheBB23/d6s3Ln50/3/ http://jsfiddle.net/TheBB23/d6s3Ln50/3/

I am pretty sure that the problem is with the javascript:我很确定问题出在 javascript 上:

document.getElementById(mobilemenuitems a).addEventListener('click', function(e) {
  document.getElementById('mobilemenuitems').remove();
});

I believe you are trying to hide the div with class mobilemenuspace when any of the links inside it are clicked.我相信当单击其中的任何链接时,您正在尝试使用 class mobilemenuspace隐藏 div。 To do so, you can use the following -为此,您可以使用以下内容 -

$('a').click(function(e){
    e.preventDefault();
    if ($(this).parents('.mobilemenuspace').length) {
        $('.mobilemenuspace').hide();
    }
});

Working sample - https://jsfiddle.net/zv18xuhL/工作样本 - https://jsfiddle.net/zv18xuhL/

A pure JS solution forked from your Fiddle -从您的 Fiddle 分叉的纯 JS 解决方案 -

http://jsfiddle.net/e69snqjk/ http://jsfiddle.net/e69snqjk/

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

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