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的随机数。