为什么&此脚本返回的位置未定义

Why & Where Is This Script Returning Undefined?

本文关键字:返回 位置 未定义 脚本 amp 为什么      更新时间:2023-09-26

我正试图使用以下代码将#(标签)附加到URL,以关闭使用CSS :target属性构建的灯箱。这个脚本在'esc'键的keydown上执行得很好,但只返回example.com/#undefined而不是example.com/#

我很抱歉是一个JS初学者,但我如何定义它只返回单个#

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

返回#undefined而不是仅返回#

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

现在,这个问题的解决方案将取决于问题中没有分享的细节,比如html是什么样子的,它应该何时以及如何工作等等

如果你想得到目标元素的href,那么你可以使用

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

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