Javascript I';我在$(';a[href*=#]';)处收到非法字符错误。每个(函数()。可能的原因是什么?

Javascript I';我在$(';a[href*=#]';)处收到非法字符错误。每个(函数()。可能的原因是什么?,javascript,jquery,Javascript,Jquery,jquery文件也包括在内…… 它使用的引号有错误吗?可以替换什么 <!----- JQUERY FOR SLIDING NAVIGATION ---> <script> $(document).ready(function() { $('a[href*=#]').each(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//

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>

$(文档).ready(函数(){
$('a[href*=#]')。每个(函数(){
if(location.pathname.replace(/^\/,“”)=此.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;
如果(目标美元){
var targetOffset=$target.offset().top;
}
}
});
});
由于
是一个元字符,请将
作为
字符串传递,或者尝试
转义它

试试看


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

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

 $('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就可以工作,无论有没有jQuery都可以工作

 $('a[href*="#"]').each(function() {
    //rest code
 });
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");
});