在 HTML 标签内调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8612554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:43:53  来源:igfitidea点击:

Calling javascript function inside HTML tag

javascripthtml

提问by ericbae

I have the following.

我有以下内容。

<a href="#" onclick="hello()">click me</a>

And I have a Javascript file

我有一个 Javascript 文件

$(document).ready(function() {
  function hello() {
    alert('hi');
  }
});

But when I click on "click me", the alert is not being fired. It says "hello" is not defined. I remove document.ready, and it works.

但是当我点击“点击我”时,警报没有被触发。它说“你好”没有定义。我删除了 document.ready,它可以工作。

Is this because "hello" is not being defined until the entire document is ready, but when the above "anchor" tag is being rendered, it can't find the function?

这是因为在整个文档准备好之前没有定义“hello”,但是当上面的“anchor”标签被渲染时,它找不到函数?

Is there any way I can get this to work?

有什么办法可以让它发挥作用吗?

  • I have to call javascript function from the html tag via ugly "onclick"
  • I need to keep my JS inside document.ready (there are other parts I need)
  • 我必须通过丑陋的“onclick”从 html 标签调用 javascript 函数
  • 我需要将我的 JS 放在 document.ready 中(我需要其他部分)

回答by Azade

You can also use the HREFattribute with javascript:keyword in Anchor Tag to call a JavaScript function:

您还可以在锚标记中使用带有javascript:关键字的HREF属性来调用 JavaScript 函数:

<a href="javascript:hello()">click me</a>

回答by jfriend00

Your hello()function declaration is not in the global scope so the call from the HTML which is trying to call it at the global scope can't find it. You can either fix it by moving your hello()function into the global scope:

您的hello()函数声明不在全局范围内,因此尝试在全局范围内调用它的 HTML 调用找不到它。您可以通过将您的hello()函数移动到全局范围来修复它:

function hello() {
    alert('hi');
}

$(document).ready(function() {
});

or by declaring it at the global scope:

或者通过在全局范围内声明它:

$(document).ready(function() {
  window.hello = function() {
    alert('hi');
  }
});

回答by Ayman Safadi

  1. Remove "hello()" from $(document).ready() callback.
  2. Call the "hello()" in a "click" event callback.
  1. 从 $(document).ready() 回调中删除“hello()”。
  2. 在“click”事件回调中调用“hello()”。
<a href="#" id="say_hello">click me</a>

<script type="text/javascript">
$(document).ready(function() {
    $('#say_hello').click(function() {
        hello();
    });
});

function hello() {
    alert('hi');
}
</script>

回答by Frank Rosario

The reason hello is undefined is because Hello() only exists in the context of the DomReady callback. You need to define Hello() in the global context.

hello 未定义的原因是因为 Hello() 仅存在于 DomReady 回调的上下文中。您需要在全局上下文中定义 Hello()。