I have click
event with jquery and i want to know how is selector clicked...
$('#parent').on('click','#child',function(){
//....
});
<div id="parent">
<div id="child">
</div>
</div>
$(this) is #parent
or #child
?
答案 0 :(得分:4)
这是孩子,你为什么不试试
$('#parent').on('click','#child',function(){
console.log($(this));
});
$('#parent').on('click','#child',function(){
console.log($(this));
});
&#13;
#child {
width: 50px;
height: 50px;
cursor: pointer;
background-color: orange;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div id="child"></div>
</div>
&#13;
答案 1 :(得分:3)
上下文this
与事件目标相关。在你的情况下是#child
。
此外,当id
可用时,您不需要事件委派,因此将该事件绑定如下:
$('#child').on('click',function(){
//....
});
答案 2 :(得分:3)
这称为Event delegation
,它允许我们将单个事件侦听器附加到父元素,该元素将为匹配选择器的所有后代触发,无论这些后代现在是存在还是将来添加。
所以,$(this)
这里总是将被点击的子元素引用到父元素,这里是#child
。
一个简单的动态添加元素演示:
// Attach Event
// on(events, selector, handler);
$('#container').on('click', 'a', function(event) {
event.preventDefault();
console.log('Anchor clicked!');
alert('Anchor clicked!');
});
// Create elements dynamically
$('#container').append('<a href="#output">Click me!</a>');
&#13;
body{font:12px Tahoma,Arial,Helvetica,sans-serif;color:#333;margin:20px}
h1{font-size:1.4em;margin-bottom:20px}
h2{font-size:1.2em}
#container{border:1px dashed #aaa;font-size:1em;padding:10px}
a{color:green}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Dynamically added link:</h2>
<div id="container"></div>
&#13;
答案 3 :(得分:1)
你可以写这样的东西来检查。
$(document).ready(function() {
$('#parent').on('click','#child',function(){
console.log("This:", $(this));
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
Parent
<div id="child">
CHILD (click on it)
</div>
</div>
&#13;