将 jQuery 与 Ember 操作处理程序一起使用

Using jQuery with Ember action handler

我正在尝试从 ember 控制器中的操作处理程序内部访问 jquery 对象 ($)。但它说 $ 未定义。

如何从操作处理程序访问 jQuery 对象?

以这款应用为例:

<div id="main"></div>

<script type="text/x-handlebars" data-template-name="index">
    <div id="scroll-div">
        <h1>Test Div</h1>

    </div>
    <a href="" {{action "findHeight"}}>Find height</a>
</script>

JS

App = Ember.Application.create({
    rootElement: '#main'
});

App.IndexController = Ember.ArrayController.extend({
    actions: {
        findHeight: function(){
            console.log(this.$('#scroll-div').height);
        }
    }
});

JS fiddle: http://jsfiddle.net/sisir/5ammt2fv/

我猜你需要更改:

findHeight: function(){
   console.log(this.$('#scroll-div').height);
}

关于这个:

findHeight: function(){
   console.log($('#scroll-div').height());
}

Fiddle


在代码中的这一行 console.log(this.$('#scroll-div').height); $('#scroll-div').height 这里 scroll-div 是一个 id,它的长度应该只有一个,因为每个元素的 id 应该是唯一的并获得高度其中 div 你应该使用 .height() 而不仅仅是 .height.

首先不建议在控制器中进行dom操作。更好的方法是设置 target="view" 并在那里处理此操作。然后您的代码内部操作将正常工作。如果你想在控制器本身处理它,那么使用这个代码片段

App.IndexController = Ember.ArrayController.extend({
    actions: {
        findHeight: function(){
            alert($('#scroll-div').height());
        }
    }
});