如何将JQuery代码转换为JavaScript?
我想将以下JQuery代码转换为JavaScript 我的html代码:如何将JQuery代码转换为JavaScript?,javascript,jquery,Javascript,Jquery,我想将以下JQuery代码转换为JavaScript 我的html代码: <input type="text" id="state" data-toggle="dropdown" placeholder="State"> <div class="dropdown-menu dropdown-menu-state" aria-labelledby="state" role="menu"> <a href="#" class="dropdown-item">
<input type="text" id="state" data-toggle="dropdown" placeholder="State">
<div class="dropdown-menu dropdown-menu-state" aria-labelledby="state" role="menu">
<a href="#" class="dropdown-item">value1</a>
<a href="#" class="dropdown-item">value2</a>
<a href="#" class="dropdown-item">value3</a>
</div>
Javascript代码:
document.querySelector(".dropdown-menu-state .dropdown-item").addEventListener("click", function() {
document.getElementById("state").innerHTML = this.text();
});
实际上,我想在单击后为文本输入输入一个下拉项值。
但它不起作用。您无法直接检测“选择选项”上的单击事件。相反,您可以在选择更改事件时这样做
var dropdown=document.getElementsByClassName(“下拉菜单状态”)[0];
addEventListener('change',function(){
document.getElementById(“state”).innerHTML=this.options[this.selectedIndex].text;
},假)代码>
文本1
文本2
文本3
文本4
文本5
有几点:
$(选择器)
更接近文档。queryselectoral(选择器)
而不是文档。querySelector(选择器)
。因此,您需要前者,并迭代返回的节点列表李>
- jQuery
.val(value)
将在指向具有此类属性的HTMLElement(如您的
)的对象上调用时设置.value
属性。因此,您要设置的是,而不是.innerHTML
,它不会对该元素产生任何积极影响
.text()
也是一种jQuery方法。作为一个getter,它相当于Node.textContent
document.querySelectorAll(“.dropdown menu state.dropdown item”)
.forEach(功能(元素){
元素addEventListener(“单击”,函数(){
document.getElementById(“state”).value=this.textContent;
});
});代码>
也许这个网站会对你有用
所以你可以“分而治之” “但我不能”-为什么?你有什么错误吗?没有错误!每次单击输入时,下拉列表都会打开,然后通过单击下拉列表输入值。@behi1989此代码的作用与。
document.querySelector(".dropdown-menu-state .dropdown-item").addEventListener("click", function() {
document.getElementById("state").innerHTML = this.text();
});