保留加载的复选框列表以进行多项选择

问题描述

我遵循了一个解决方案 "dropdown menu on click",非常感谢 @thisOneGuy。我可以通过左键单击 <rect> 区域来显示复选框列表。但是我遇到了一个问题,每次单击其中一个复选框时,整个列表都会消失。如果我想进行多选,我必须再次左键单击。

下面是代码。我删除了不必要的部分,只留下有用的部分,以简化描述:

HTML:

<body>
    <ul class='custom-menu'>
        <li data-action="first"><input type="checkbox"> First thing</li>
        <li data-action="second"><input type="checkbox">Second thing</li>
        <li data-action="both"><input type="checkbox">Third thing</li>
    </ul>
    <div class="container">
        <div class="row">
            <svg id="svg2">
                <g id="layer1">
                    ...
                    <rect id="rect3643" style="stroke:#000000;stroke-width:.98070;fill:none" rx="4.5514" ry="3.1535" height="24.137" width="15.424" y="494.5" x="376.52" />
                    ...
                </g> 
            </svg>
        </div>
    </div>
</body>

CSS:

.custom-menu {
    display: none;
    z-index: 1000;
    position: absolute;
    overflow: hidden;
    border: 1px solid #CCC;
    white-space: nowrap;
    font-family: sans-serif;
    background: #FFF;
    color: #333;
    border-radius: 5px;
}

.custom-menu li {
    padding: 8px 12px;
    cursor: pointer;
    list-style-type: none;
}

.custom-menu li:hover {
    background-color: #DEF;
}

Javascript:

$(document).ready(function(){
    var rects = d3.selectAll("rect");
    rects.on("click",function(event) {

        // Avoid the real one
       d3.event.preventDefault();
    
        // Show contextmenu
        $(".custom-menu").finish().toggle(100).
    
        // In the right position (the mouse)
        css({
          top: d3.event.pageY + "px",left: d3.event.pageX + "px"
        });
      });

      // If the document is clicked somewhere
    $(document).bind("mousedown",function(e) {

    // If the clicked element is not the menu
    if (!$(e.target).parents(".custom-menu").length > 0) {
  
      // Hide it
      $(".custom-menu").hide(100);
    }
  });

  // If the menu element is clicked
    $(".custom-menu li").click(function() {

    // This is the triggered action name
    switch ($(this).attr("data-action")) {
  
      // A case for each action. Your actions here
      case "first":
        polygonClicked("first");
        break;
      case "second":
        polygonClicked("second");
        break;
      case "both":
        polygonClicked("first");
        polygonClicked("second");
        break;
    }
  
    // Hide it AFTER the action was triggered
    $(".custom-menu").hide(100);
  });
}); 

我在css上没有做太多改动,在JS中做了一些修改。函数 polygonClicked(e) 是我编写的用于更改其他多边形背景的函数。

有人可以帮助我使列表可以进行多项选择,并且只有在我单击列表区域外时才会消失吗?

解决方法

您可以简单地从您共享的代码中删除最后一行 $(".custom-menu").hide(100);,该代码在点击列表项时隐藏菜单。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...