2.$()函数的认识和使用

2015-05-01  本文已影响40人  futurefeeling

我们通过jQuery的各种选择符和方法取得的结果集合会被包装在 jQery对象 中。通过jQery对象,实际地对操作这些元素会变得非常简单。

注意:jQery对象与常规的DOM元素不同,而且没有必要为实现某些任务给纯DOM元素或节点列表添加相同的方法和属性。原因后面会讲((●ˇ∀ˇ●))

为了创建jQery对象,就要使用 <code>$()</code> 函数。这个函数接受 css选择符 作为参数,充当的是一个中间转换角色,返回包含页面中对应元素的jQery对象。

如果你对css选择器不熟悉,或者想了解更多,可以参考 jQery 备忘手册

举例说明,如何使用$()函数。(下面的例子都是基于 **bootstrap **的,如果你想要看下面代码的运行效果,你需要引入bootstrap的 <code>js</code> 文件和 <code>css</code> 文件,当然,还有我们的 jQery框架 )

<style>
        .tab-location {
            text-indent: 2em;
        }
        .center-location {
            text-align: center;
        }
        thead {
            font-size: 16px;;
            font-weight: bold;
        }
</style>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <table>
                <thead>
                    <tr>
                        <td>选择器</td>
                        <td>匹配</td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>*</td>
                        <td>所有元素</td>
                    </tr>
                    <tr>
                        <td>#id</td>
                        <td>带有给定ID的元素</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script>
    $(document).ready(function(){
        $('table').addClass('table table-striped');
        $('tr').find('td:first-child').addClass('tab-location');
        $('thead').find('tr').find('td:nth-child(2)').addClass('center-location');
    });
</script>

效果前:


不加上js的效果

效果如下:


加上js的效果

下面对js的代码进行分析:

    $(document).ready(function(){
        $('table').addClass('table table-striped');
        $('tr').find('td:first-child').addClass('tab-location');
        $('thead').find('tr').find('td:nth-child(2)').addClass('center-location');
    });

上面的 <code>$('table')</code> 返回了一个DOM对象,<code>$('tr')</code> 也返回了一个DOM对象......

对于 <code>$()</code> 函数我们暂时就认识那么多,只要的把握点是,这个函数返回了一个对象集;

关于DOM你可以参考我另一篇文字 DOM 初接触

上一篇 下一篇

猜你喜欢

热点阅读