我当前正在使用Bootstrap 4导航栏,并且有一个带语言的下拉菜单,选择了下拉菜单选项后,将其显示。
我确实使用过jQuery,但需要知道如何在没有它的情况下进行操作。
$(".dropdown-menu a ").click(function() {
$(this).parents(".dropdown").find('.btn').text($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
English
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" data-value="english">EN</a></li>
<li><a href="#" data-value="thai">TH</a></li>
</ul>
</div>
答案 0 :(得分:0)
您必须根据类名称获取元素,然后在其上添加事件侦听器。
var divs = document.querySelectorAll('.dropdown-item');
var myFunction = function() {
alert('Click');
};
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', myFunction, false);
}
答案 1 :(得分:0)
您可以将点击侦听器分配给以下列表项
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
English
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" data-value="english" onclick = "setLang('english')">EN</a></li>
<li><a href="#" data-value="thai" onclick = "setLang('thai')">TH</a></li>
</ul>
</div>
<script>
function setLang(language){
document.getElementById("dropdownMenu1").innerHTML = language;
}
</script>
答案 2 :(得分:0)
这是一个尝试,但是我想说使用jq要简单得多
<IonFab slot="fixed" vertical="bottom" horizontal="end">
<IonFabButton>
<IonIcon name="add" />
</IonFabButton>
<IonFabList side="top">
<IonFabButton color="primary">
<IonIcon name="document" />
<input type="file" onChange={appendScene} hidden style={{opacity: 0, width: "1px", height: "1px"}}/>
<IonInput readonly></IonInput>
</IonFabButton>
<IonFabButton color="secondary">
<IonIcon name="folder" />
</IonFabButton>
</IonFabList>
</IonFab>
document.querySelectorAll(".dropdown-menu a").forEach(a=>{
// Assign a click to each element
a.addEventListener("click", function(){
// get the closest eg (parents) and then seacrh for the button
// when you wrote text i assumed you ment innerhtml.
a.closest(".dropdown").querySelectorAll(".btn")[0].innerHTML = a.innerHTML;
})
})