简体   繁体   English

在HTML标记内调用javascript函数

[英]Calling javascript function inside HTML tag

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" 我必须通过丑陋的“onclick”从html标签调用javascript函数
  • I need to keep my JS inside document.ready (there are other parts I need) 我需要将我的JS保存在document.ready中(我还需要其他部分)

您还可以在Anchor Tag中使用HREF属性和javascript: keyword来调用JavaScript函数:

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

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. 您的hello()函数声明不在全局范围内,因此来自尝试在全局范围内调用它的HTML的调用无法找到它。 You can either fix it by moving your hello() function into the global scope: 您可以通过将hello()函数移动到全局范围来修复它:

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

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

or by declaring it at the global scope: 或者在全球范围内宣布:

$(document).ready(function() {
  window.hello = function() {
    alert('hi');
  }
});
  1. Remove "hello()" from $(document).ready() callback. 从$(document).ready()回调中删除“hello()”。
  2. Call the "hello()" in a "click" event callback. 在“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>

The reason hello is undefined is because Hello() only exists in the context of the DomReady callback. hello未定义的原因是因为Hello()仅存在于DomReady回调的上下文中。 You need to define Hello() in the global context. 您需要在全局上下文中定义Hello()。

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

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