I'我在$('a[href*=#]').each(function)处得到非法字符错误.可能的原

I'm getting the illegal character error at $('a[href*=#]').each(function(). what could be the possible reasons?

本文关键字:非法 字符 function 错误 我在 href each      更新时间:2023-09-26

jquery文件也包含在内
它使用的引号有错误吗?什么可以替换?

<!----- JQUERY FOR SLIDING NAVIGATION --->   
<script>
$(document).ready(function() {
    $('a[href*=#]').each(function() {
        if (location.pathname.replace(/^'//, '') == this.pathname.replace(/^'//, '')
                && location.hostname == this.hostname
                && this.hash.replace(/#/, '')) {
            var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']');
            var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
            if ($target) {
                var targetOffset = $target.offset().top;
            }
        }
    });
});
</script>

由于#是元字符,因此将#作为string传递,或者只尝试将其作为escape

试试,

$('a[href*="#"]').each(function() {

$('a[href*=''#]').each(function() {

请阅读此处了解更多有关元字符的信息。

名称属性中有特殊字符。因此用引号括起来:

 $('a[href*="#"]').each(function() {
    //rest code
 });

如果我可以建议一种普通的方法。

document.links已经返回页面中的所有链接。Array.filter过滤数组,但它是泛型的。

你可以通过如下散列来过滤链接:

var filter = Array.prototype.filter;
var withHash = filter.call(document.links,function(a){ return a.hash; });
// withHash now contains all links with a # hash
withHash.forEach(function(el){
    console.log(el," is an anchor element");
});

考虑到您已经在代码中使用了.hash,这似乎更自然。它也不需要jQuery工作,无论有没有它都可以工作。