【问题标题】:Uncaught TypeError: Object [object Object] has no method 'on'未捕获的类型错误:对象 [object Object] 没有“on”方法
【发布时间】:2012-06-06 10:23:21
【问题描述】:

谁能帮我解决这个问题?

当我使用最新(或新)版本的 jQuery 时,下面的小脚本可以正常工作。但是,当我使用旧版本的 jQuery 时,我的脚本显示 on 函数不存在。

这是我的脚本,它不适用于旧版本的 jQuery:

$(document).ready(function () {
    $(".theImage").on("click", function(){
        // In the event clicked, find image, fade slowly to .01 opacity
        $(this).find("img").fadeTo("slow", .01).end()
        // Then, of siblings, find all images and fade slowly to 100% opacity
               .siblings().find("img").fadeTo("slow", 1);           
    })
})

感谢任何形式的帮助。

【问题讨论】:

    标签: jquery onclick bind


    【解决方案1】:

    您必须使用bind 而不是on,因为on 仅在jQuery 1.7 中引入。

    $(document).ready(function () {
        $(".theImage").bind("click", function(){
            // In the event clicked, find image, fade slowly to .01 opacity
            $(this).find("img").fadeTo("slow", .01).end()
            // Then, of siblings, find all images and fade slowly to 100% opacity
            .siblings().find("img").fadeTo("slow", 1);           
        })
    })
    

    【讨论】:

    • 哇,这个人真快... 12 分钟后我可以接受答案。我会检查它是否正确...效果很好!
    • @Christoph 用户在问为什么他的代码(.on())不能与旧版本的 jQuery 一起使用......所以这个答案很好
    • @Alex - 在这种情况下,bindon 的功能相同。没有选择器被传递给on,这将导致它委托事件处理程序。
    • @F.Calderan 答案根本没有解决它的为什么,尽管这个问题从来没有具体问过为什么。它只是说“这就是解决方案”,而没有解释最初的问题是什么;我会让人们自己决定这是否构成完整的答案。
    • 当然每个人都为自己选择 :) 对我来说很好,因为它解决了问题 - 这是对已删除评论的回复
    【解决方案2】:

    您可以使用delegate(),例如:

    $("table").delegate("td", "click", function() {
      $(this).toggleClass("chosen");
    });
    

    这相当于使用on()编写的以下代码:

    $("table").on("click", "td", function() {
      $(this).toggleClass("chosen");
    });
    

    【讨论】:

    • 虽然您在答案中描述的等价是正确的,但 delegate() not 等同于 OP 在问题中对 on() 的使用(他将元素直接附加到.theImage,当你委托给另一个元素时)。
    • 仅供参考:从 jQuery 1.7 开始,delegate() 已被 on() 取代
    【解决方案3】:

    您必须使用 jQuery 版本 1.7+ 才能使用 on()bind() 已弃用。

    【讨论】:

    • 谢谢,不知道为什么人们不赞成,但我给了 1.7 并且成功了!
    【解决方案4】:

    on函数改为bind

    .children().on("click",function()

    .children().bind("click",function()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-08
      • 2013-04-19
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多