javascript - 如何将每个标题属性放入输入标签的值中?

标签 javascript html

我试图将每个标题属性获取到输入标记的值中,但我尝试了很多方法,但都失败了,我什至尝试使用 for() 循环。

例如这是我在添加javascript之前的代码

<div class="all">
  <div class="myOtherClass">
    <a class="getTitle test" href="#" Title="i want grab this title">click me to change</a>
  </div>
  <div class="myOtherClass">
    <a class="getTitle test" href="#" Title="i want grab this too">click me to change</a>
  </div>
  <div class="myOtherClass">
    <a class="getTitle test" href="#" Title="same at 2 other">click me to change</a>
  </div>
  <div class="Otherclass">
    <input class="myInput" type="button" value=""/>
  </div>
</div>
<小时/>

这就是我试图做的

let getTitle = document.querySelectorAll('.getTitle').forEach((f) => {
    f.addEventListener('click', function() {
     document.querySelectorAll('.all').forEach(item =>{

      let button = item.querySelector('.getinput')          
      let a = item.querySelectorAll('.test');
       for(let i=0; i < a.length; i++){
          let atitle = a[i];
          button.value = atitle.title; 
        }
       })
      })
     }) 
<小时/>

这就是我希望我的代码在添加 javascript 后执行的操作

when i click on the first a tag is will return the value in input is

<input class="myInput" type="button" value="i want grab this title"/>
<小时/>

And when i click the second a tag will return this value

<input class="myInput" type="button" value="i want grab this too"/>
<小时/>

但我做出的结果就是这样

when i click on the first a tag is return the value in input is

<input class="myInput" type="button" value="i want grab this title"/>
<小时/>

And when i click the second a tag is return the same value of the first a tag

<input class="myInput" type="button" value="i want grab this title"/>

有没有办法解决这个问题?

最佳答案

您可以在每个 anchor 标记上使用事件监听器,并通过 ID 设置输入的值,您需要相应地更改该值:

const elements = document.getElementsByClassName('getTitle')
const input = document.getElementById('[change_this]')
Array.from(elements).forEach(a => {
  a.addEventListener('click', (el) => {
    input.value = el.target.title
  })
})
<div class="all">
  <div class="myOtherClass">
    <a class="getTitle test" Title="i want grab this title">click me to change</a>
  </div>
  <div class="myOtherClass">
    <a class="getTitle test" Title="i want grab this too">click me to change</a>
  </div>
  <div class="myOtherClass">
    <a class="getTitle test" Title="same at 2 other">click me to change</a>
  </div>
  <div class="Otherclass">
    <input id="[change_this]" class="myInput" type="button" value="" />
  </div>

关于javascript - 如何将每个标题属性放入输入标签的值中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56182614/

相关文章:

html - 使标题行和表格数据与水平滚动条协调移动

html - 如何将HTML添加到文本中并添加到DOM中显示?

javascript - 使用主 gitignore 文件 gitignore 子文件夹

javascript - 如何使用 plunker 或 jsfiddle 运行 angular2 代码

javascript - D3 - 如何正确标记 x 轴

javascript - 是否可以将新打开的窗口移动到另一台显示器?

javascript - HTML Canvas 矩形内的阴影效果

c# - 用 C# 缩小 JavaScript

html - 我如何让我的链接靠近 Logo ?

javascript - 动态更改 iframe 内的元素样式