简体   繁体   English

如何在onclick属性中编写jQuery代码或调用jQuery函数

[英]How to write jQuery code or call jQuery function in onclick attribute

Why doesn't this simple code work? 为什么这个简单的代码不起作用?

<div onClick="myFunction()"></div>
$(document).ready(function(){
    function myFunction(){
       alert("sss");
    }
})

The JS file is external and it's called in the head of my HTML page. JS文件是外部文件,在我的HTML页面的head调用。 The jQuery library is added before that. 在此之前添加了jQuery库。

It doesn't work as functions called from the on* event attributes need to be within scope of the window . 它不起作用,因为从on*事件属性调用的函数必须在window范围内。 Your code places the function within the jQuery document.ready handler instead. 您的代码会将函数放置在jQuery document.ready处理程序中。 Try this: 尝试这个:

 function myFunction() { alert("sss"); } 
 <div onClick="myFunction()">Click me</div> 

You should note though, that using on* event attributes is considered outdated for this reason, amongst many. 但是,您应该注意,由于许多原因,使用on*事件属性被认为已过时。 You should instead use unobtrusive JS code to attach your event handlers, either in native JS: 相反,您应该在本机JS中使用简洁的JS代码来附加事件处理程序:

 document.querySelector('div').addEventListener('click', function() { alert("sss"); }); 
 <div>Click me</div> 

Or jQuery, as you seem to be using it already: 或jQuery,因为您似乎已经在使用它:

 $(function() { $('div').on('click', function() { alert("sss"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Click me</div> 

First Go and read tutorials of html and Jquery at some tutorial websites like This or thisone . 首先,在Thisthisone等一些教程网站上阅读html和Jquery的教程。

and answer to your code is 并回答您的代码是

HTML 的HTML

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

Javascript Java脚本

function myFunction() {
    alert('Hello');
} 

Assuming you included JQuery libraries. 假设您包括JQuery库。

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

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