[英]Javascript, HTML and onClick - Function is not defined
I'm trying to make an "Insert link" button to a Rich Text Editor in Javascript.我正在尝试在 Javascript 中为富文本编辑器制作一个“插入链接”按钮。 Basically, what it'll do is adding the following code to its content:
基本上,它将做的是将以下代码添加到其内容中:
<a href="linkGoesHere" onClick="someJSFunction();"> textGoesHere </a>
The catch is, someJSFunction()
must fire when the user clicks on the button inside the editor itself.问题是,当用户点击编辑器内部的按钮时,
someJSFunction()
必须触发。 I wrote a Javascript function which adds that code when the Insert Link button is clicked on, like this:我编写了一个 Javascript 函数,它在单击“插入链接”按钮时添加该代码,如下所示:
editor.setContent(previousContent + theHtmlCode);
However, when I click on the link someJSFunction()
doesn't fire, and instead I get a "Function is not defined" error.但是,当我单击链接时
someJSFunction()
不会触发,而是收到“未定义函数”错误。 I tried to define someJSFunction()
in the global scope, but it still won't see it.我试图在全局范围内定义
someJSFunction()
,但它仍然看不到它。 The weird thing is, even if I do something ugly like adding奇怪的是,即使我做了一些丑陋的事情,比如添加
<script type="text/javascript"> *(I define someJSFunction() here)* </script> <a href="linkGoesHere" onClick="someJSFunction();"> textGoesHere </a>
to the editor's content it'll still throw the same error.对于编辑器的内容,它仍然会抛出相同的错误。 I've seen a few people in SO with the same problem, but they somehow managed to solve it by defining their functions in the global scope.
我在 SO 中看到一些人遇到同样的问题,但他们设法通过在全局范围内定义他们的函数来解决它。
Notice that I can't edit the HTML code directly, which is why I have to resort to using a piece of Javscript which will insert a piece of HTML which in turn will call another piece of Javascript.请注意,我无法直接编辑 HTML 代码,这就是为什么我必须使用一段 Javscript 来插入一段 HTML,而后者又会调用另一段 Javascript。
And before you ask, no, I won't use JQuery.在你问之前,不,我不会使用 JQuery。
The code below should works.下面的代码应该可以工作。
HTML HTML
<textarea id="editor"></textarea>
<a id="link" href="#">Link</a>
Javascript Javascript
var link = document.getElementById('link');
link.addEventListener('click', editContent);
function editContent() {
var editor = document.getElementById('editor');
editor.value += "text";
}
The jsfiddle for the example above https://jsfiddle.net/ar54w16L/上面例子的jsfiddle https://jsfiddle.net/ar54w16L/
Enjoy !享受!
在html中尝试onclick
而不是onClick
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.