如何将每个标题属性转换为输入标签的值?

时间:2019-05-17 08:33:41

标签: javascript html

我试图将每个title属性获取到输入标签的值中,但是我尝试了很多方法,但是所有尝试都失败了,我什至尝试使用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后执行的操作

  

当我单击第一个标签时,将返回输入值为

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

  

当我单击第二个标签时,该标签将返回该值

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

但是我的结果就是这样

  

当我单击第一个标签时,返回输入值

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

  

当我单击第二个标签时,返回第一个标签的相同值

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

有没有办法解决这个解决方案?

2 个答案:

答案 0 :(得分:1)

您可以在每个锚标记上使用事件侦听器,并通过 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>

答案 1 :(得分:0)

从可以理解的内容到您的操作:

old string: allOf(withId(someinfo), withContentDescription("Text"))
new string:  allOf(withId(someinfo)) 
document.querySelectorAll('.getTitle').forEach( Z_elm => {
  Z_elm.addEventListener('click', function () {
    document.querySelector('.myInput').value = this.title;

    // or : (in your real code)
    // document.querySelector('#myModal .getinput').value = this.title;
  })
})
a {cursor: pointer;}