2、jQuery选择器与方法(Head First笔记)

jQuery click()

点击p元素后,将弹出对话框。

$("p").click( function() {
    alert("You rang?");
});

扩展:

Definition and Usage

The click event occurs when an element is clicked.

The click() method triggers the click event, or attaches a function to run when a click event occurs.

Syntax

Trigger the click event for the selected elements:

$(selector).click()

Attach a function to the click event:

$(selector).click(function)

选择器

类选择器

通过类名来选择元素

$(".nav").click( function() {
    alert("You clicked me!");
});

ID选择器

通过ID来选额元素

$("#my_blurb").slideToggle("slow");

扩展:

The element Selector

The jQuery element selector selects elements based on the element name.

You can select all

elements on a page like this:

$("p");

jQuery append()

$("p").append(" <strong>Like me, for instance.</strong>");

没使用append()之前的HTML代码:

<p>
    jQuery lets me add stuff onto my web page without having to reload it.
</p>

使用append()之后的HTML代码:

<p>
    jQuery lets me add stuff onto my web page without having to reload it. 
    <strong>Like me, for instance.</strong>
</p>

也就是说,用了jQuery append()之后,strong标签的内容插入到p标签内,成为了p标签的子元素,并且插入的位置是原来p标签内的子元素的后面。

扩展:

jQuery prepend() Method

Definition and Usage:

The prepend() method inserts specified content at the beginning of the selected elements.

Syntax

$(selector).prepend(content,function(index,html))

content:
Require.
Specifies the content to insert (can contain HTML tags).
Possible values: HTML elements, jQuery objects, DOM elements.

// Create content with HTML, jQuery and DOM
function prependText() {
    var txt1 = "<p>Text.</p>";              // Create text with HTML
    var txt2 = $("<p></p>").text("Text.");  // Create text with jQuery
    var txt3 = document.createElement("p");
    txt3.innerHTML = "Text.";               // Create text with DOM
    $("p").prepend(txt1, txt2, txt3);       // Prepend new elements
}

function(index, html):
Optional.
Specifies a function that returns the content to insert.
index - Returns the index position of the element in the set
html - Returns the current HTML of the selected element

$(document).ready(function(){
    $("button").click(function(){
        $("p").prepend(function(index, html){
            return "<b>This p element has index " + index + "</b>."  + html;
        });
    });
});

用$(this)返回当前元素

点击了id为myImg这个元素,这个元素就会执行slideUp();

$("#myImg").click( function() {
    $(this).slideUp();
});

jQuery remove()

点击id为#btnRemove这个元素,会把li元素全部删除。

$("#btnRemove").click(function() {
    $("li").remove();
})

Math.floor()与Math.random()

Math.floor()向下取整。

Math.floor(1.6) // 1

Math.random()将返回一个介于0和1的随机数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值