Javascript,HTML和onClick - 函数未定义 [英] Javascript, HTML and onClick - Function is not defined
问题描述
我正在尝试在Javascript中向富文本编辑器添加插入链接按钮。基本上,它会做的是将以下代码添加到其内容:
< a href =linkGoesHereonClick = someJSFunction(); > textGoesHere< / a>
结果是, someJSFunction()
必须当用户点击编辑器本身的按钮时触发。我写了一个Javascript函数,在单击插入链接按钮时添加了该代码,如下所示:
editor.setContent(previousContent + theHtmlCode);
然而,当我点击链接 someJSFunction()
不会触发,而是会出现功能未定义错误。我试图在全局范围内定义 someJSFunction()
,但它仍然不会看到它。奇怪的是,即使我做了一些丑陋的事情,比如添加
< script type =text / javascript> *(我在这里定义了一些JSFunction())*< / script> < a href =linkGoesHereonClick =someJSFunction();> textGoesHere< / a>
到编辑器的内容,它仍然会抛出同样的错误。我曾经见过一些SO的同样的问题,但他们设法通过在全球范围内定义它们的功能来解决它。
请注意, t直接编辑HTML代码,这就是为什么我不得不求助于使用一块Javscript,它会插入一段HTML,然后再调用另一块Javascript。
- 避免事件声明HTML
- 避免常量
下面的代码应该可以工作。 b
$ b
HTML
< textarea id =editor>< / textarea>
< a id =linkhref =#>连结< / a>
Javascript
var oLink = document.getElementById('link');
oLink.addEventListener('click',editContent);
function editContent(){
var oEditor = document.getElementById('editor');
oEditor.value + =text;
以上示例的jsfiddle https://jsfiddle.net/za20w2a4/1/
享受!
I'm trying to make an "Insert link" button to a Rich Text Editor in 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. I wrote a Javascript function which adds that code when the Insert Link button is clicked on, like this:
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. I tried to define someJSFunction()
in the global scope, but it still won't see it. 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.
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.
And before you ask, no, I won't use JQuery.
- Avoid event declare in HTML
- Avoid constant
The code below should works.
HTML
<textarea id="editor"></textarea>
<a id="link" href="#">Link</a>
Javascript
var oLink = document.getElementById('link');
oLink.addEventListener('click', editContent);
function editContent() {
var oEditor = document.getElementById('editor');
oEditor.value += "text";
}
The jsfiddle for the example above https://jsfiddle.net/za20w2a4/1/
Enjoy !
这篇关于Javascript,HTML和onClick - 函数未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!