这个脚本为什么以及在哪里返回未定义的?

Why & Where Is This Script Returning Undefined?

我正在尝试使用以下代码将 #(主题标签)附加到 URL 以关闭使用 CSS :target 构建的灯箱属性。此脚本在按下 'esc' 键时执行得很好,但是 returns example.com/#undefined 而不是 example.com/#.

作为一个 JS 初学者,我深表歉意,但是我如何将它定义为 return 只是一个 #

$( document ).on( 'keydown', function ( e ) {
    if ( e.keyCode === 27 ) {
        var href = this.href;
        window.location.hash = href;
    }
});

Returns #undefined 而不仅仅是 #.

答案是,在您的处理程序中,this 指的是没有 href 属性 值的 document 对象。所以你的 href 变量的值为 undefined 因此哈希更新为 undefined.

现在,问题的解决方案将取决于问题中未共享的细节,例如 html 的外观如何、何时以及如何工作等

你想获取目标元素的href,那么你可以使用

var href = e.target.href || '';

var href = $(e.target).closest('[href]').attr('href') || '';