[英]jQuery event propagation does not work as expected
I am trying to propagate events with jQuery using the code below: 我正在尝试使用以下代码通过jQuery传播事件:
$(document).ready(function() {
$('#main').click(function(e){
var el = e.target.nodeName;
var $jObj = $(el);//jQuery object
$jObj.css('color','green');
});
});
This is the simple html code: 这是简单的html代码:
<div id="main">
<p>Test one</p>
<p>Test two</p>
<p>Test three</p>
</div>
Now, If I click on one of the p elements not only the selected p changes the color to green, but all p . 现在,如果我单击p元素之一,不仅选定的p会将颜色更改为绿色,而且所有p也会更改。 I cannot understand the resaon.
我不明白这个原因。 According to the jQuery script above only the selected
<p>
should change the colour. 根据上面的jQuery脚本,只有选定的
<p>
可以更改颜色。 What I am doing wrong? 我做错了什么?
According to the jQuery script above only the selected
p
根据上面的jQuery脚本,仅选择了
p
I doubt that. 我不信。 You are selecting all
p
elements: 您正在选择所有
p
元素:
var el = e.target.nodeName; // el = "P"
var $jObj = $(el);//jQuery object // equiv to $("p")
e.target.nodeName
is the value "P"
which you then use as selector, and $("P")
selects all p
elements. e.target.nodeName
是值"P"
,然后将其用作选择器,而$("P")
选择所有 p
元素。
To only select the event target, pass the DOM element itself to jQuery: 要仅选择事件目标,请将DOM元素本身传递给jQuery:
$(e.target)
Relevant documentation: jQuery(element)
, event.target
. 相关文档:
jQuery(element)
, event.target
。
$(document).ready(function() { $('#main').click(function(e){ var $jObj = $(e.target);//jQuery object $jObj.css('color','green'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="main"> <p>Test one</p> <p>Test two</p> <p>Test three</p> </div>
Try this out : 试试看:
$(document).ready(function() {
$('#main > p').click(function(e){
$(this).css('color','green');
});
});
$(document).ready(function() { $('#main').find('p').on('click', function(){ $(this).css('color','green'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="main"> <p>Test one</p> <p>Test two</p> <p>Test three</p> </div>
Try this way to event delegate using on
of JQUERY
, when you click on p
element, assign this
to a variable and then use it as selector object before apply css 尝试用这种方式来事件委托
on
的JQUERY
,当你点击p
元素,赋予this
一个变量,然后用它作为选择对象之前应用CSS
$(document).ready(function()
{
$('#main').on('click','p',function(e)
{
var el = this;
var $jObj = $(el);//jQuery object, see here carefully
$jObj.css('color','green');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.