BackboneJS view.$(selector)方法

如果jQuery包含在页面上,在每个视图具有运行视图的元素中范围里查询一个$函数。如果使用该范围内的jQuery函数,不必使用模型ID作为查询拉出的具体内容在列表的一部分,并且可以依靠更多的HTML类属性。这等同于运行: view.$el.find(selector)

语法

view.$(selector)

参数:

  • selector:  使用不同类型的选择,如ID或类。

显示

<!DOCTYPE html>
   <head>
      <title>View Example</title>
         <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script>
   </head>
   <body>
   <div id="myVal">
        <button id="button" data-test="">Click Here</button>
    </div>
   <span id="myLog"></span>
      <script type="text/javascript">

        //The variable contains id selector as 'mydata'
         var myLog = $('#mydata');

         //The variable 'data' is used to display the values
         var data = function(val) {
            document.write(val);
         };

         //'ViewDemo' is a name of the view class
         var ViewDemo = Backbone.View.extend({

         //When click event occurs it activates the defined functions 'myFunc1' and 'myFunc2'
            events: {
               'click [data-test]' : 'myFunc1',
               'click *[data-test]': 'myFunc2',
            },

            //'el' uses '#myVal' as the view reference
            el: $('#myVal'),

            //When user clicks the button, it refers to the button defined within the 'div' tag and
            //it will display the below statements
            myFunc1: function () {
               data('Hello...');
            },
            myFunc2: function () {
               data('Welcome to xuhuhu.com...');
            }
        });

        //'myview' is an instance of the 'ViewDemo' class
        var myview = new ViewDemo();
      </script>
   </body>
</html>

输出

让我们进行以下步骤来看看上面的代码工作:

  • 保存上述代码到dollar-jquery.html文件

  • 在浏览器打开这个HTML文件。


上一篇: BackboneJS view.attributes 下一篇: BackboneJS view.template(data)方法