首页 > > > jquery学习手记(4)元素的选择与操作
一. 选择元素
id选择器,示例为:
1 // Selecting elements by ID
2 $("#myId"); // note IDs must be unique per page类名选择器,示例为:
1 // Selecting elements by class name
2 $(".myClass");属性选择器,示例为:
1 // Selecting elements by attribute
2 $("input[name='first_name']"); // beware, this can be very slow in older browsers复杂css选择器,示例为:
1 // Selecting elements by compound CSS selector
2 $("#contents ul.people li");伪选择器,示例为:
// Pseudo-selectors
$("a.external:first");
$("tr:odd");
// select all input-like elements in a form (more on this below)
$("#myForm :input");
$("div:visible");
// all except the first three divs
$("div:gt(2)");
// all currently animated divs
$("div:animated");注意:
1.伪选择器使用:visible 和:hidden时,jquery只是测试此元素的真实可见性,而不是css的可见性或者呈现。jquery用来检测此元素在页面的物理高度和宽度是否都大于0.
2.这种测试不能和<tr>一起使用。当和<tr>一起使用时,jquery检查css的呈现属性,当呈现属性被设置为none的时候,该元素会被隐藏。
3.元素没有加入到DOM上的都视为不可见的。即使css设置元素的属性为可见,也不起作用。
二. 选择选择器。
jquery提供了许多基于属性的选择器,这些选择器允许使用简单的规则表达式(基于任意属性的内容)来选择。示例如下:
1 // find all <a>s whose rel attribute
2 // ends with "thinger"
3 $("a[rel$='thinger']");测试元素是否存在:
1 //Testing whether a selection contains elements
2 if ( $("div.foo").length ) {
3 ...
4 }保存元素:
var $divs = $("div");重新定义和过滤元素:
1 // Refining selections
2 $("div.foo").has("p"); // div.foo elements that contain <p> tags
3 $("h1").not(".bar"); // h1 elements that don't have a class of bar
4 $("ul li").filter(".current"); // unordered list items with class of current
5 $("ul li").first(); // just the first unordered list item
6 $("ul li").eq( 5 ); // the sixth选择表单元素:
注意:为了浏览器有更好的性能,使用 [type = "element"] 而不是:element伪选择器.
1 // :button pseudo-selector
2 // selects <button> elements and elements with type="button"
3 $("form :button");1 // :checkbox pseudo-selector
2 // selects elements with type="checkbox"
3 $("form :checkbox");1 // :checked pseudo-selector
2 // selects checked checkboxes and radio buttons
3 $("form :checked");1 // :disabled pseudo-selector
2 // selects all input elements with the disabled attribute
3 $("form :disabled");1 // :enabled pseudo-selector
2 // selects all elements that do not have the disabled attribute
3 $("form :enabled");1 // :file pseudo-selector
2 // selects all inputs with a type = "file"
3 $("form :file");1 // :image pseudo-selector
2 // selects all input elements of type "image"
3 $("form :image");// :input pseudo-selector
// selects <input>, <textarea>, <select>, and <button> elements
$("form :input");1 // :password pseudo-selector
2 //targets any <input>s with a type of password
3 $("form :password");// :radio pseudo-selector
// selects all <input>s of type "radio"
$("form :radio");1 // Selection associated radio buttons with :radio
2 // selects all radio buttons with the name attribute of gender
3 $("form input[name="gender"]:radio")// :reset pseudo-selector
// selects all elements of type "reset"
$("form :reset");// :selected pseudo-selector
// selects all selected items in <option> elements
$("form :selected");// :submit pseudo-selector
// selects all inputs with type = "submit"
$("form :submit");// :text pseudo-selector
// selects all inputs with type = "text"
$("form :text");使用选择表达式
get/set方法
1 //The $.fn.html method used as a setter
2 $("h1").html("hello world");
3
4 // The html method used as a getter
5 $("h1").html();Set方法返回一个jquery对象,允许你在选择表达式中继续调用jquery方法。
Get方法根据你要求返回的结果,因此就不能在get方法的返回值中继续调用jquery方法。
例如:
// Attempting to call a jQuery method after calling a getter
// This will NOT work
$("h1").html().addClass("test")链式结构
如果你使用的选择表达式返回的是jquery对象,那么你就可以继续调用jquery对象的方法而不用使用分号作为中止符号,这种形式就像一个链条一样:
// Chaining
$("#content").find("h3").eq( 2 ).html("new text for the third h3!");但通常为了可读性而把上述选择表达式拆分成如下形式:
1 // Formatting chained code
2 $("#content")
3 .find("h3")
4 .eq( 2 )
5 .html("new text for the third h3!");同样jquery也提供了一个方法在链式表达式中间返回对象:$.fn.end。例如:
1 // Restoring your original selection using $.fn.end
2 $("#content")
3 .find("h3")
4 .eq( 2 )
5 .html("new text for the third h3!")
6 .end() // restores the selection to all h3s in #content
7 .eq( 0 )
8 .html("new text for the first h3!");注意:选择表达式可能会影响所有的元素,如果仅要修改一个元素,请注意使用正确的表达式。例如:
// Changing the HTML of an element
$("#myDiv p:first").html("New <strong>first</strong> paragraph!");
在DOM中移动元素的方法很多,通常使用的方法有两种:
放置一个选定的元素以另一个元素为坐标。
放置一个元素以选定元素为坐标。
例如:jquery提供的$.fn.insertAfter 和$.fn.after方法。
$.fn.insertAfter方法放置选定元素在参数中提供的元素位置之后。
$.fn.after方法放置元素位于参数中提供的选定元素之后。
其他别的方法还有:
$.fn.insertBefore / $.fn.before, $.fn.appendTo / $.fn.append, and $.fn.prependTo / $.fn.prepend.
实例如下:
1 // Moving elements using different approaches
2
3
4
5 // make the first list item the last list item
6
7 var $li = $("#myList li:first").appendTo("#myList");
8
9
10
11 // another approach to the same problem
12
13 $("#myList").append( $("#myList li:first") );
14
15
16
17 // note that there's no way to access the
18
19 // list item that we moved, as this returns
20
21 // the list itself
// Making a copy of an element
// copy the first list item to the end of the list
$("#myList li:first").clone().appendTo("#myList");
注意:如果你需要复制相关的数据及事件,请给$.fn.clone传递true参数。
从页面移除元素的方法有两种:$.fn.remove 和$.fn.detach。
$.fn.remove一次性永久移除元素所有的数据和事件。
$.fn.detach保留元素的数据和事件,可以恢复。
如果你仅向移除一个元素的内容而在此页面上保留这个元素,请使用$.fn.empty来舍弃元素的内部html。
创建新元素Jquery使用$()来创建一个新的元素。示例如下:
// Creating new elements from an HTML string
$("<p>This is a new paragraph</p>");
$("<li class=\"new\">new list item</li>");
// Creating a new element with an attribute object
$( "<a/>", {
html : "This is a <strong>new</strong> link",
"class" : "new",
href : "foo.html"
});
当新建一个元素时,通常不能离开就增加到页面上。如果想立即把一个元素加入到页面,可以使用如下的方法:
// Getting a new element on to the page
var $myNewElement = $("<p>New element</p>");
$myNewElement.appendTo("#content");
$myNewElement.insertAfter("ul:last"); // this will remove the p from #content!
$("ul").last().after( $myNewElement.clone() ); // clone the p so now we have 2
或者不使用引用来保存元素:
// Creating and adding an element to the page at the same time
$("ul").append("<li>list item</li>");
批量添加元素的方法,为了性能的考虑,请使用array来收集所有的元素,然后把它们一起加入到页面,例如:
var myItems = [];
var $myList = $("#myList");
for ( var i = 0; i < 100; i++ ) {
myItems.push( "<li>item " + i + "</li>" );
}
$myList.append( myItems.join("") );
操作属性操作属性的示例如下:
// Manipulating a single attribute
$("#myDiv a:first").attr( "href", "newDestination.html" );
// Manipulating multiple attributes
$("#myDiv a:first").attr({
href: "newDestination.html",
rel: "super-special"
});
// Using a function to determine an attribute's new value
$("#myDiv a:first").attr({
rel: "super-special",
href: function( idx, href ) {
return "/new/" + href;
}
});
$("#myDiv a:first").attr( "href", function( idx, href ) {
return "/new/" + href;
});
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69901620/viewspace-3136248/ ,如需转载,请注明出处,否则将追究法律责任。