javascript - 如何将 JQuery 代码转换为 JavaScript?
问题描述
我想将以下 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">value1</a>
<a href="#" class="dropdown-item">value2</a>
<a href="#" class="dropdown-item">value3</a>
</div>
jQuery代码:
$('.dropdown-menu-state .dropdown-item').on('click', function(){
$("#state").val($(this).text());
});
Javascript代码:
document.querySelector(".dropdown-menu-state .dropdown-item").addEventListener("click", function() {
document.getElementById("state").innerHTML = this.text();
});
实际上,我想在单击后在文本输入中输入一个下拉项值。但它不起作用。
解决方案
几点:
$(selector)
document.querySelectorAll(selector)
比更接近document.querySelector(selector)
。所以你会想要前者,并遍历返回的NodeList。- jQuery
.val( value )
将在.value
指向具有此类属性的 HTMLElement 的对象上调用时设置该属性(例如您的<input>
)。因此,您要设置的内容,而不是.innerHTML
不会对此元素产生任何积极影响的内容。 .text()
也是一个jQuery方法。作为吸气剂,它相当于Node.textContent
.
document.querySelectorAll(".dropdown-menu-state .dropdown-item")
.forEach( function( elem ) {
elem.addEventListener("click", function() {
document.getElementById("state").value = this.textContent;
});
});
<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>
推荐阅读
- python - python2和python3的兼容python文字
- stripe-payments - 带有定价矩阵的条带订阅
- web-scraping - Python网页抓取希腊字母未显示
- c# - 在 wpf 中使用多重绑定时如何设置verticalAlignment?
- php - 如何使正则表达式或程序替换以下逻辑
- apache-flink - Flink WaterMark 和触发器 - 事件时间未丢弃的后期元素?
- php - Symfony 2 在用户接受条款之前不会创建任何 cookie
- javascript - 方法返回意外错误
- sass - node-sass 不编译新添加的 scss 文件
- php - 检查输入中是否不是 url 地址 Laravel