这件事让我很困惑 我尝试获取 anchor 属性并用这种方式将其替换为输入 id,但如果 anchor 具有更长的 id,事情就不起作用了。如何在没有符号的情况下获取 id#
$('.srcFilter a').click(function(e){
e.preventDefault();
var a = $(this).attr('href');
var b = a.slice(1,6);
$('input').attr( 'id',b);
})
a{
margin-right:10px;
}
<input id="srcAll" />
<div class="srcFilter">
<a href="#item1">all</a>
<a href="#item2">item</a>
<a href="#item3">code</a>
<a href="#itemlong">item long</a>
</div>
最佳答案
试试这个。
[].forEach.call(document.querySelectorAll('a'), function(e){
e.addEventListener('click', function() {
var h = e.href;
h = h.split("#")[1];
// alternatives
// h = h.substr(1, h.length); -- might not fit every situation
// h = h.match('#(.*)');
let inp = e.parentNode.previousElementSibling;
inp.setAttribute('id', h);
inp.value = "May id is: "+h; //debugging -))
});
})
<input id="srcAll" />
<div class="srcFilter">
<a href="#item1">all</a>
<a href="#item2">item</a>
<a href="#item3">code</a>
<a href="#itemlong">item long</a>
</div>
关于javascript - 如何在没有 # 符号的情况下获取 attr id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42154493/