我试图创建一个函数,通过它我可以知道被点击的元素是否是文本节点。
var isTextNode = function(target){
return $(target).contents().filter(function(){
return this.nodeType === 3;
});
};
$(document).on('click',function(e){
//console.log(e.target);
if(isTextNode(e.target).length === 1){
console.log('clicked');
}
});

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>
Lorem ipsum dolor sit amet <!-- clicking here should log "clicked" -->
<span class="pull-right">
<i class="fa fa-twitter"></i> <!-- clicking here should do nothing -->
100 <!-- clicking here should log "clicked" -->
</span>
</h4>
<div>
plain text <!-- clicking here should log "clicked" -->
</div>
<img src="" width="300" height="300" /> <!-- clicking here should do nothing -->
&#13;
但是,我无法生成正确的代码。
答案 0 :(得分:0)
可能像
$(document).on('click',function(e){
if($(e.target).text() != ""){
console.log('clicked');
}
// prevent event bubbling down the DOM-tree
return false;
});