下拉按钮仅适用一次

时间:2018-01-19 01:35:36

标签: javascript jquery html css

我正在尝试在HTML表格中放置一个按钮,该按钮在单击时显示下拉菜单,在单击时或用户在菜单外单击时关闭。它只能工作一次,然后按钮似乎完全停止工作。控制台上没有错误引导我朝着正确的方向前进。码: HTML:

<tr>
    <td><?php echo $row['first_name']; ?></td>
    <td><?php echo $row['last_name']; ?></td>
    <td><?php echo $row['u_email']; ?></td>
    <td><?php echo $row['partynumber']; ?></td>
    <td><?php echo $time; ?></td>
    <td class="dropcontainer"><button class="ellipsis" class="dropbtn" onclick="toggleDrop();">. . .</button>
        <div id="resDrop" class="dropdown-content">
            <a href="#">Seated</a>
            <a href="#">Cancelled</a>
            <a href="#">No Show</a>
            <?php if($row['notes'] != ""){ ?>
            <a href="#">Notes</a>
            <?php } ?>
        </div>
    </td>
</tr>

Javascript:

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function toggleDrop() {
  if (document.getElementById("resDrop").style.display != "block"){
    document.getElementById("resDrop").style.display = "block";
    document.getElementById("maindiv").innerHTML = document.getElementById("CurrentRes").innerHTML;
  }else{
    document.getElementById("resDrop").style.display = "none";
    document.getElementById("maindiv").innerHTML = document.getElementById("CurrentRes").innerHTML;
  }
}

$('html').click(function() {
   $('.dropdown-content').hide();
});

$('.dropcontainer').click(function(event){
  event.stopPropagation();
});

CSS:

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

1 个答案:

答案 0 :(得分:1)

首次加载页面时,您可以通过其ID访问resDrop元素。在那之后,我怀疑你是在动态地重新创建你的内容,这就是造成你的问题的原因(虽然你的代码还不够,100%肯定你正在做的..... )

您需要对动态创建的元素执行的操作是将其操作与非动态父级相关联。

e.g。

 <button class="ellipsis" class="dropbtn" id="toggle-button" >. . .</button>

$(document).on("click", "#toggle-button", function () { 
    if($("#resDrop").css( "display" ) !== 'block') {
        $("#resDrop").css( "display", 'block' );
    } else {
        $("#resDrop").css( "display", 'none' );
    }

    $("#maindiv").html($("#CurrentRes").html());
})

在上面的示例中,我已经为您的切换按钮添加了一个ID,然后我将此事件处理程序附加到document,因此如果您动态重新创建按钮,它仍然可以正常工作

我已经使用jquery重写了你的切换功能。

相关问题