【问题标题】:How to call coffeescript function with parameter? [closed]如何使用参数调用coffeescript函数? [关闭]
【发布时间】:2016-07-17 00:12:13
【问题描述】:

我创建了一个 coffescript 函数,其参数如下所示:

enlargeSelectionOn : (zoneSelected) ->
  $(zoneSelected).stop().animate 
    width:450
    height:510
    1000

html 部分如下所示:

 #container1
    .title1
        img(src="img/team.png")
        span.text First Title
        a(href="#")

CSS 部分(带有手写笔)看起来像

#container1
  width 398px
  height 490px
  float left
  margin-right 11px
  border 2px solid $color6
  background-color $color5
  border-bottom-right-radius: 50px;
  box-shadow 4px 4px 8px #aaa
  .title1
    height 53px
    width 100%
    border-bottom 1px solid $color6
    color white
    background-color $color6

我创建了当我悬停它时为 div 的维度设置动画的函数 所以我想用悬停事件来调用它:

    'hover div#container1' : 'enlargeSelectionOn("container1")'

但它不起作用!我知道我的代码有问题

当我没有像这样的参数调用它时

  'hover div#container' : 'enlargeSelectionOn'

正常工作

但在这种情况下,我不得不在我的函数中调用选定的 div

enlargeSelectionOn : () ->
  $('div#container1').stop().animate 
    width:450
    height:510
    1000

我想使用参数,因为我打算将此函数用于不同的 div 容器。

【问题讨论】:

  • 你想达到什么目的?您的问题缺少一些上下文(html 部分)。
  • 我只想用悬停事件调用我的函数!如果没有参数功能,这可能很容易,但是使用参数我不知道正确的语法来做到这一点
  • 使用= 分配给变量。 : 应该用于分配对象键。在这里,您正在创建一个(未命名的)对象,而不是将函数分配给 enlargeSelectionOn
  • 你在使用某种框架吗?您说您正在与 'hover div#container1' : 'enlargeSelectionOn("container1")' 绑定事件,但绑定事件的是什么?
  • 你应该已经包含了主干.js 标签,这是非常重要的信息。 Backbone 允许events 中的匿名函数,所以你可以说'hover div#container1' : function() { this.enlargeSelectionOn("container1") }。我可能会选择currentTarget,然后走上 DOM 来找到你要找的东西。

标签: javascript jquery backbone.js coffeescript


【解决方案1】:

我不认为您编写函数的方式是正确的语法。应该是:

enlargeSelectionOn = (zoneSelected) ->
  $(zoneSelected).stop().animate 
    width:450
    height:510
    1000

要在悬停事件上调用此函数,您需要告诉 jQuery 在您的 div 悬停时调用函数enlargeSelectionOn。为此,请使用以下代码:

$("div#container").hover(enlargeSelectionOn("container1"))

更多关于悬停功能的信息请见in the jQuery docs

【讨论】:

  • 感谢您的回复,但我编写函数的方式是正确的,因为它适用于其他没有参数的函数,甚至我调用函数的方式在没有参数函数的情况下仍然正确!我不知道使用参数调用函数的正确语法
  • @L.Ezz 你的函数可能是正确的,但你没有将它分配给enlargeSelectionOn。查看生成的输出。
  • 哦,好的。 @L.Ezz 用参数调用函数,比如'hover div#container' : enlargeSelectionOn("container1") 这应该在div#container 悬停时调用放大选择函数。
  • @user2367593:你确定吗?这将在定义该对象时调用enlargeSelectionOn,而不是在触发悬停事件时。
猜你喜欢
  • 2011-10-06
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多