2017-06-01 62 views
1

我試圖做一個功能,我可以知道點擊的元素是文本節點與否。檢測點擊的目標是文本節點

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 -->

但是,我不可能產生正確的代碼。

回答

0

可能像

$(document).on('click',function(e){ 

    if($(e.target).text() != ""){ 
     console.log('clicked'); 
    } 
    // prevent event bubbling down the DOM-tree 
    return false; 
});