jQuery ondiv上的div [英] Jquery onclick on div
本文介绍了jQuery ondiv上的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的问题.以下代码适用于所有标签:
I have a simple question. The following code works for all the tags:
$('*').click(function(e) {
alert(1);
});
但是,当我为id为"content"的div尝试以下代码时:
But, when I try this code for the div with id "content":
$('#content').click(function(e) {
alert(1);
});
我在做什么错了?
推荐答案
确保它位于文档就绪标签内;或者,尝试使用.live
Make sure it's within a document ready tagAlternatively, try using .live
$(document).ready(function(){
$('#content').live('click', function(e) {
alert(1);
});
});
示例:
$(document).ready(function() {
$('#content').click(function(e) {
alert(1);
});
});
#content {
padding: 20px;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="content">Hello world</div>
从jQuery 1.7开始,不推荐使用.live()方法.使用.on()附加事件处理程序.
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
$('#content').on( "click", function() {
alert(1);
});
这篇关于jQuery ondiv上的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文