我试图在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;
}
最佳答案
页面首次加载时,可以通过其ID访问resDrop
元素。在那之后,我怀疑您是在动态地重新创建内容,这就是导致您出现问题的原因(尽管您的代码不够多,无法100%确定您正在执行的操作.....)
您需要对动态创建的元素执行的操作是将其操作与非动态父元素相关联。
例如
<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重新编写了您的切换功能。
关于javascript - 下拉按钮只能使用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48332899/