检测单击img元素

时间:2017-01-30 11:46:40

标签: javascript jquery html click

<div class="portfolio-item">
 <div class="hover-bg">
   <a href="#">
    <div class="hover-text">
     <h4>Logo Design</h4>
     <small>Branding</small>
     <div class="clearfix"></div>
     <i class="fa fa-plus"></i>
    </div>
    <img src="01.jpg" class="img-responsive ng-isolate-scope">
   </a>
  </div>
 </div>
</div>

我正在尝试检测<img/>元素的点击次数。我有以下听众:

$('img').addEventListener 'click', ((event) ->
  console.log event
), false

...但事件不会发生。如何检测点击事件?

2 个答案:

答案 0 :(得分:0)

我建议您使用.on("click")代替.click()

 $('img').on("click", function() {
   console.log("image clicked");
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="portfolio-item">
  <div class="hover-bg">
    <a href="#">
      <div class="hover-text">
        <h4>Logo Design</h4>
        <small>Branding</small>
        <div class="clearfix"></div>
        <i class="fa fa-plus"></i>
      </div>
      <img src="01.jpg" class="img-responsive ng-isolate-scope">
    </a>
  </div>
</div>

答案 1 :(得分:0)

您可以按如下方式使用jQuery click事件:

$(document).ready(function(){
    $("img").click(function(){
        alert("The image was clicked.");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div class="portfolio-item">
 <div class="hover-bg">
   <a href="#">
    <div class="hover-text">
     <h4>Logo Design</h4>
     <small>Branding</small>
     <div class="clearfix"></div>
     <i class="fa fa-plus"></i>
    </div>
    <img src="http://placehold.it/140x100" class="img-responsive ng-isolate-scope">
   </a>
  </div>
 </div>
</div>