首页 > 解决方案 > 使用 javascript 获取锚标记 URL

问题描述

我正在尝试将锚标记的 url 存储在变量中,但我不断收到错误消息。

var buttonUrl = document.getElementById('test').href;

Uncaught TypeError: Cannot read property 'href' of null

标签: javascript

解决方案


确保您的代码在窗口加载后正在运行:

window.onload = function() {
    var buttonUrl = document.getElementById("test").href;
    console.log(buttonUrl);
    //This will log the href of the "test" element to the console as a debugger. You can now use buttonUrl as you want.
}

推荐阅读