我在这里从无序列表构建了一个菜单。当您选择一项时,它会将类别切换为事件。我想做的是在用户选择一个元素后,从这个未排序的列表中获取 HTML 或数据目标的值。在下面的示例中,我想检索 External 或 external 并将其存储在一个变量中,我可以在选择结束后传递给 ajax/php。
.options {
list-style: none;
padding: 0;
margin: 0 -4px 0;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.options:before,
.options:after {
content: "";
display: table;
clear: both;
}
.options li {
padding: 4px;
-webkit-box-flex: 1;
-ms-flex: 1 1 calc(100% / 3);
flex: 1 1 calc(100% / 3);
}
.options li a {
display: block;
padding: 8px 4px;
text-align: center;
font-family: "Ubuntu", sans-serif;
text-transform: uppercase;
font-weight: 700;
background: #30343b;
color: #fff;
border-radius: 4px;
border: 2px solid transparent;
-webkit-transition: border-color .3s ease, color .3s ease;
transition: border-color .3s ease, color .3s ease;
}
.options li a:active {
color: rgba(255, 255, 255, 0.6);
}
.options li a.active {
border-color: #0d71d9;
}
<ul class="options">
<li><a class="active" href="#" data-target="external">External</a></li>
<li><a href="#" data-target="internal">Internal</a></li>
<li><a href="#" data-target="both">Both</a></li>
</ul>
最佳答案
如果你想从点击的链接中获取data-target
属性,你可以使用getAttribute('data-target')
如果你想获得被点击的元素 html
使用 innerHTML
注意:在下面的示例中,我获得了所有的data-target
和innerHTML
。如果你只想要 active
的,你要么把这段代码放在你添加 .active
类的函数中,要么在 link
的声明中> 你使用 .options li a.active
请参阅下面的代码段。
const link = document.querySelectorAll('.options li a');
for (let i = 0; i < link.length; i += 1) {
link[i].onclick = function() {
const dataTarget = this.getAttribute('data-target');
const targetHtml = this.innerHTML;
console.log(dataTarget, targetHtml)
};
}
<ul class="options">
<li><a class="active" href="#" data-target="external">External</a></li>
<li><a href="#" data-target="internal">Internal</a></li>
<li><a href="#" data-target="both">Both</a></li>
</ul>
关于javascript - 如何从无序列表制作的菜单中的选定元素中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51395404/