我试图将每个标题属性获取到输入标记的值中,但我尝试了很多方法,但都失败了,我什至尝试使用 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/