且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

未捕获的类型错误:无法读取未定义的属性“hasAttribute"

更新时间:2022-10-28 11:20:09

您在选择器字符串中缺少尾随 ".更改为:

document.querySelectorAll('[role="tablist"]')[0];

I am using a script from the W3C to create accessible tab panels. When I load the page with the script, I get the error Uncaught TypeError: Cannot read property 'hasAttribute' of undefined for a variable tablist which is defined as follows:

var tablist = document.querySelectorAll('[role="tablist]')[0];
var tabs, panels;
var delay = determineDelay();

The code that the error refers to:

// Determine delay
function determineDelay () {
    var hasDelay = tablist.hasAttribute('data-delay');
    var delay = 0;

    if (hasDelay) {
        var delayValue = tablist.getAttribute('data-delay');
        if (delayValue) {
            delay = delayValue
        } else {
            delay = 300;
        }
    }

    return delay;
}

And the HTML tablist is supposed to grab is:

<div role="tablist" aria-label="Options">
   <button role="tab" aria-selected="true" aria-controls="general-tab" id="general-btn">General</button>
   <button role="tab" aria-selected="false" aria-controls="social-tab" id="social-btn" tabindex="-1">Social Networks</button>
</div>

This is being loaded via a WordPress plugin that is enqueued as:

wp_enqueue_script( 'enhap-admin-script', plugins_url( '../_js/enhap.js', __FILE__ ), array(), false, true );

I cannot see anything wrong with the script. I tried manually typing the var command in the console and got the same result.

You're missing a trailing " in the selector string. Change to:

document.querySelectorAll('[role="tablist"]')[0];