用于将文本插入输入的多个按钮

我正在尝试为我们最常见的搜索提供一个带有搜索值的按钮。我想做的是用户单击按钮并插入带有引号“Some Text”的文本。


现在,这就是我使用的单个按钮。我该如何做到这一点,以便我可以使用一个带有多个按钮的脚本?


  <button onclick="searchText()" data-product-name="iPhone 12 Pro">iPhone 12 Pro Max</button> <----Current Button


<button onclick="searchText()" data-product-name="Pixel 5">Pixel</button> <---- Added for what Id like

<button onclick="searchText()" data-product-name="LG">LG</button><---- Added for what Id like

<button onclick="searchText()" data-product-name="Samsung S20 Plus">Samsung S20 Plus</button><---- Added for what Id like


  <script>

  var i = 0;

  var txt = '"iPhone 12 Pro Max"';

  var speed = 50;


  function searchText() {

    if (i < txt.length) {

      document.getElementById("search-query").value += txt.charAt(i);

      i++;

      setTimeout(typeWriter, speed);

    }

  }

  </script>

我尝试添加以下内容但没有成功。


var txt = element.getAttribute('data-product-name');


哆啦的时光机
浏览 139回答 2
2回答

萧十郎

var i = 0;var txt = '"iPhone 12 Pro Max"';var speed = 50;var elements = document.querySelectorAll('button')for (let i = 0; i < elements.length; i++) {&nbsp; elements[i].addEventListener('click', function() {&nbsp; &nbsp; var txt = this.getAttribute('data-product-name');&nbsp; &nbsp; console.log(txt);&nbsp; });}<button data-product-name="iPhone 12 Pro">iPhone 12 Pro Max</button><button data-product-name="Pixel 5">Pixel</button><button data-product-name="LG">LG</button><button data-product-name="Samsung S20 Plus">Samsung S20 Plus</button>

慕姐8265434

您可以将按钮的 id 传递给 searchText。并使用 jquery 或纯 js 读取文本&nbsp; &nbsp;<!--html --->&nbsp; &nbsp;<button onclick="searchText('buttonOne')" id= "buttonOne" data-product-name="Samsung S20 Plus">Samsung S20 Plus</button><---- Added for what Id like&nbsp; &nbsp;// javascript&nbsp; &nbsp;function(buttonId){&nbsp; &nbsp; &nbsp; &nbsp; var text = document.getElementById(buttonId).innerHTML&nbsp; &nbsp; &nbsp; &nbsp; // process the text with your business logic here&nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript