首页 > 解决方案 > 如何将 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();
});

实际上,我想在单击后在文本输入中输入一个下拉项值。但它不起作用。

标签: javascriptjquery

解决方案


几点:

  • $(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>


推荐阅读