作者:化妆造型师艾米 | 来源:互联网 | 2023-01-30 13:26
我有text content
一个boxed
元素,div
但是当我点击boxed
元素时仍然会发生变化,而我只需要在点击时进行更改text content
.
这是代码:https://jsfiddle.net/Issact/u0g8LLLo/
some text
some text
JS:
$(document).on('click','div', function(){
if (!$(this).text().trim().length > 0) {
$(this).text("foo");
} else {
$(this).append('You clicked on a text');
}
});
Ori Drori..
5
将事件处理程序绑定到节点或使用事件委派时,请this
引用事件绑定到的节点(或在事件的情况下委托给该节点on
).
单击.box
第一个div
元素内部,获取div
as this
.由于div
元素包含文本,因此结果错误.
相反,你应该得到事件目标.目标是点击的实际元素.
$(document).on('click', 'div', function(e) {
var $target = $(e.target); // the event target
if (!$target.text().trim().length > 0) {
$target.text("foo");
} else {
$target.append('You clicked on a text');
}
});
.box {
background-color: green;
height: 50px;
width: 50px;
display: block;
}
some text
some text
1> Ori Drori..:
将事件处理程序绑定到节点或使用事件委派时,请this
引用事件绑定到的节点(或在事件的情况下委托给该节点on
).
单击.box
第一个div
元素内部,获取div
as this
.由于div
元素包含文本,因此结果错误.
相反,你应该得到事件目标.目标是点击的实际元素.
$(document).on('click', 'div', function(e) {
var $target = $(e.target); // the event target
if (!$target.text().trim().length > 0) {
$target.text("foo");
} else {
$target.append('You clicked on a text');
}
});
.box {
background-color: green;
height: 50px;
width: 50px;
display: block;
}
some text
some text