简体   繁体   English

通过 href 链接到 JavaScript 函数

[英]Link to a JavaScript function via href

I'm struggling in linking an HTML link <a> with a JavaScript function using Google Apps Script.我正在努力使用 Google Apps 脚本将 HTML 链接<a>与 JavaScript 函数链接起来。 I tried the following, but it left me with this error message:我尝试了以下操作,但它给我留下了此错误消息:

"Unsafe JavaScript attempt to initiate navigation for frame with origin ' https://script.google.com ' from frame with URL 'different url'. The frame attempting navigation must be same-origin with the target if navigating to a javascript: url" “不安全的 JavaScript 尝试从具有 URL '不同 url' 的框架中为源为 ' https://script.google.com ' 的框架启动导航。如果导航到 javascript: url,则尝试导航的框架必须与目标同源”

My code:我的代码:

var link = document.createElement("a");
link.setAttribute("href", "javascript:test()");
link.textContent = "Click";

//----------------------------------------------
function test() {
    console.log("Test");
}

The code is placed in an HTML file between:代码被放置在一个 HTML 文件中:

<script>
</script>

Everything is coded in the IDE of Google Apps Script.一切都在 Google Apps Script 的 IDE 中编码。

don't use href.不要使用href。 Use the onclick event for JavaScript functions.对 JavaScript 函数使用 onclick 事件。

Use the onclick javascript function instead:改用 onclick javascript 函数:

<a onclick="myFunction()">Click me</a>

https://www.w3schools.com/jsref/event_onclick.asp https://www.w3schools.com/jsref/event_onclick.asp

href is an attribute used to define the target of the link. href是用于定义链接目标的属性。 The right attribute to use for click-triggered events is onclick .用于点击触发事件的正确属性是onclick

See the W3C documentation for href and onclick有关hrefonclick 的信息,请参阅 W3C 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM