如何在没有 # 符号的情况下获取 attr id

how to get attr id without # sign

这件事让我很困惑 我尝试获取锚点属性并用这种方式将其替换为输入 id,但如果锚点具有更长的 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>

使用:

var b = a.substr(1);

当您省略 substr()length 参数时,它默认为字符串的其余部分。

使用.substr(1)获取不带0-index'#'的锚点属性并添加jquery。查看结果:

$('.srcFilter a').on('click',function(e){
  e.preventDefault();
  var a = $(this).attr('href');
  var b = a.substr(1);
  $('input').attr('id',b);
        console.log(b);
 });
a{
margin-right:10px;
}
<script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<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>

检查这个,

$('.srcFilter a').click(function(e){
        e.preventDefault();
        var a = $(this).attr('href');
        var b = a.substring(1); // var b = a.substr(1);
        $('input#srcAll').attr('id',b);
});

试一试,它会起作用。