我让自己陷入一片混乱。当点击跨度中的每个“...”时,我希望包含“报告”的myDropdown div显示在跨度旁边。 然后我想在单击相应的报告时返回“elementid”类的id,在这种情况下为1或2,但我不确定在reportFunction中放入什么
<html>
<style>
.dropbtn {
background-color: white;
color: black;
padding: 2px;
font-size: 30px;
border: none;
cursor: pointer;
font-weight: bold;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
background-color: #f9f9f9;
min-width: 160px;
font-size:10px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
border: 1px solid lightgrey;
z-index: 1;
float: left;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #f1f1f1;cursor:pointer;}
.show {display:block;}
</style>
<span class="dropdown">
<button onclick="myFunction()" class="dropbtn">...</button>
<div id="myDropdown" class="dropdown-content">
<a class="elementid" id="1">Report</a>
</div>
</span>
<p>
<span class="dropdown">
<button onclick="myFunction()" class="dropbtn">...</button>
<div id="myDropdown" class="dropdown-content">
<a class="elementid" id="2">Report</a>
</div>
</span>
<script>
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
var id = document.getElementsByID("id");
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
function reportFunction() {
}
</script>
</html>
答案 0 :(得分:1)
这样的东西可以让你得到你想要的id。它使用parent()
进入包含范围,然后获取包含类elementId
的元素。
function reportFunction() {
var id = $(this).parent().find('.elementid');
... //whatever you need to do
}
您的代码有其他问题。您有两个div
元素具有相同的ID myDropdown
。您当前使用getElementById
的代码将始终获得第一个代码。您需要指定一个类而不是ID,并以与上面相同的方式获取正确的类,或者使用您删除的一个div
并根据需要附加到正确的范围。