An error will be reported when clicking show is not defined
Why just put the show() function outside $(function(){})?
typecho2017-07-05 10:39:03
The html you append is a string, and the event in onclick is show(). If the method of a specific object is not specified, it will look for the global method by default, and $(function(){}) is a closure
给我你的怀抱2017-07-05 10:39:03
Write it like this
$(function() {
leftMenu();
function show() {
alert('hhhhhhhh');
}
function leftMenu() {
var html = '<p class="show" onclick="'+show()+'">click me</dv>'
$('#box').append(html);
}
})
Call show() directly and it will be executed immediately. If it is written as onclick="show()", $(document).ready() is executed after the document is loaded. When the page structure is completed, you click to trigger show (), at this time, you will search for show() under the window. Of course, the result is undefined. If you really want to write it in $(funciton(){}), you can do this:
$(function() {
leftMenu();
/*function show() {
alert('hhhhhhhh');
}*/
function leftMenu() {
var html = '<p class="show">click me</dv>'
$('#box').append(html);
}
//做个事件委托
$('body').on('click', $('.show'), function() {
alert('aaaaa')
})
})
怪我咯2017-07-05 10:39:03
The show function is inside an anonymous function. The onclick binding will search globally and cannot find things defined in the anonymous function
天蓬老师2017-07-05 10:39:03
onclick will find the custom function show() under the window object, which is window.shou(). . So it should be placed outside the $(function(){}) function. . Therefore, in the future, all custom functions should be written outside $(function(){}), and some subsequent processing and calls should be placed inside $(function(){}) to ensure that they are called after the document is loaded
黄舟2017-07-05 10:39:03
In plain language: $(function(){}) is to execute the content after the document is executed
And you added the binding after the document is loaded. Show() was not found when he executed html, please adopt it
某草草2017-07-05 10:39:03
In fact, it is a problem caused by the scope of js. onclick="show()" executes the show() method in window, but there is no such method in Window.
伊谢尔伦2017-07-05 10:39:03
Because, $(function(){}) = $.ready(), that is to say, the function show is declared after the page is loaded, but you write show() in the onclick event in the line, and the show function at this time has not yet been statement, so it will be reported as not defined