javascript - 从 URL 在网页内执行 javascript 函数?

标签 javascript html

我有这个 HTML 代码:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display an alert box:</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>

</body>
</html>

然后我将这段代码保存为:C:/js.html

然后我在浏览器的地址栏中写:

file:///C:/js.html#javascript:myFunction();

但是Javascript函数没有执行。为什么?

我怎样才能让它工作?

最佳答案

试试这个短片。使用 #test 作为 url index.html#test 的位置部分访问您的页面。

function myHash() {
    alert('here iam!');
}

function hash() {
    var hash = location.hash;

    switch(hash) {
        case '#test' : myHash();
            break;
        default : break;
    }
}

hash();

关于javascript - 从 URL 在网页内执行 javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31687911/

相关文章:

javascript - React 422 中的 Axios.post,错误 : (Data Validation Failed.)

javascript - Testcafe 从元素中获取文本

javascript - 悬停时居中展开文本

javascript - 当鼠标在图像上移动时,如何使文本颜色发生变化

javascript - 带有 mootools 问题的多 Accordion

javascript - 如何使用 javascript 单击 chrome 中的按钮

javascript - Angular 1.4 并在 JavaScript 中使用 ngAnimate

html - IE 11 伪元素::之前的绝对背景

javascript img 加载()

jquery - 使用 jQuery 替换图像