【问题标题】:Adding extra functions to an image's onmouseout attribute向图像的 onmouseout 属性添加额外的功能
【发布时间】:2011-08-01 10:24:32
【问题描述】:

我有这个:

<img border="0" onmouseout="hidetips();" onmouseover="showtips();" src="image.gif">

<script type="text/javascript">
$(document).ready(function() {
    $("img").each(function(index){
        $(this).attr("onmouseout", "hidetips();newfunction();");
    });
});
</script>

我在上面尝试过,但它不起作用,有人知道如何在 onmouseout 属性后面添加额外的 newfunction() 吗?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    使用mouseout 方法绑定事件处理程序。使用匿名函数来包含对单独函数的调用:

    $(document).ready(function() {
      $("img").mouseout(function() {
        hidetips();
        newfunction();
      });
    });
    

    注意:它将绑定jQuery对象中所有找到的元素,因此您不必循环。

    编辑:

    你也可以使用 jQuery 绑定showtips 函数,这样你就不需要每个图像元素中的事件属性:

    $(document).ready(function() {
      $("img").mouseover(showtips).mouseout(function() {
        hidetips();
        newfunction();
      });
    });
    

    【讨论】:

      【解决方案2】:

      或者,您可以添加一个名为 clickHandler 或类似的函数,然后从那里根据需要运行尽可能多的函数,因此您只需指定 onmouseoutonmouseover 中的一个函数。例如:

      <img border="0" onmouseout="clickhandler();" onmouseover="showtips();" src="image.gif">
      
      <script type='text/javascript'>
          function clickhandler()
          {
              hidetips();
              newfunction();
          }
          function hidetips()
          {
              alert('hide');
          }
          function newfunction()
          {
              alert('newfunction');
          }
          function showtips()
          {
              alert('showtips');
          }
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-13
        • 1970-01-01
        • 2012-01-13
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多