<ul> <li>list <strong>item 1</strong></li> <li><span>list item 2</span></li> <li>list item 3</li></ul>
$("ul").click(function(event) { var $target = $(event.target); if ( $target.is("li") ) {$target.css("background-color", "red"); }});如此,便可以限制住,只有列表项li本身点击之后,才会触发写入的点击事件.
// 是不是一个divelem.is("div") && console.log("it"s a div");// 是不是有包含(也可以有其他类名)bigbox的类名的元素?elem.is(".bigbox") && console.log("it has the bigbox class!");// 是不是隐藏的?elem.is(":not(:visible)") && console.log("it is hidden!");这里有一点需要注意,&&运算符可以用来做一个判断,当前面的条件满足时,后面的会执行,但是后面的条件不能是表达式,只能是console.log()或则++i一类的.
elem.animate({"width":200},1000);// 是否正在动画elem.is(":animated") && console.log("it is animated!");2.jquery中拓展方法
elem.animate({"width":200},1000);// 是否正在动画elem.is(":animated") && console.log("it is animated!");便为 jQuery 添加一个为add 的 “静态方法”,之后便可以在引入 jQuery 的地方,使用这个方法了,
jQuery.fn.exists = function(){ return this.length > 0; }console.log($("#elem").exists() ? "exists!" : "doesn"t exist!");3.jQuery方法$()实际上是拥有两个参数的
$("li","#firstList").each(function(){console.log($(this).html());});这里,第二个参数用来限制第一个参数给定的查找结果
$("<div>",{"class": "bigBlue","css": {"background-color":"purple"},"width" : 20,"height": 20,"animate" : {// 可以设置div的动画效果"width": 200,"height":50}}).appendTo("#result");这里,第二个参数用来对创建的元素进行设置.
<ul id="meals"> <li> <ul class="breakfast"> <li class="eggs">No</li> <li class="toast">No</li> <li class="juice">No</li> </ul> </li> </ul>
breakfast.find(".eggs").text("Yes").end() // back to breakfast.find(".toast").text("Yes").end().find(".juice").toggleClass("juice coffee").text("Yes");这里,end()会返回查找元素的上一级.
$(function(){$(document).on("contextmenu",function(e){e.preventDefault();});});当然,应用此事件,也可以自定义,右键出来的操作菜单,类似于
6.有时候不希望网页的某一部分内容被选择比如复制粘贴这种事情,我们可以这么做:$("p.descr").attr("unselectable", "on").css("user-select", "none").on("selectstart", false);
这样,内容就不能再被选择了.
7.最小的DOM操作
用js操作DOM是非常浪费资源的,下面的方法一般是我们通常的做法:
var elem = $("#elem");for(var i = 0; i < 100; i++){elem.append("<li>element "+i+"</li>");}这样做,重复的向元素中添加,无疑是一种极大的资源浪费,而通过下面的方法,则可以减少大量的DOM操作
var elem = $("#elem"),arr = [];for(var i = 0; i < 100; i++){arr.push("<li>element "+i+"</li>");}elem.append(arr.join(""));8.更方便的分解URL
var url = "http://tutorialzine.com/books/jquery-trickshots?trick=12&&abc=123#comments";var a = $("<a>",{ href: url });console.log(url); console.log("Host name: " + a.prop("hostname")); //Host name: tutorialzine.comconsole.log("Path: " + a.prop("pathname")); //Path: /books/jquery-trickshotsconsole.log("Query: " + a.prop("search")); //Query: ?trick=12&&abc=123console.log("Protocol: " + a.prop("protocol")); //Protocol: http:console.log("Hash: " + a.prop("hash")); //Hash: #comments这样我们就可以很快速的完成URL的分解
$("#pancakes li").eq(0).remove();$("#pancakes li").eq(1).remove();$("#pancakes li").eq(2).remove();第二种和第三种,可以二选一:
//第二种var pancakes = $("#pancakes li");pancakes.eq(0).remove();pancakes.eq(1).remove();pancakes.eq(2).remove();//第三种pancakes.eq(0).remove().end().eq(1).remove().end().eq(2).remove().end();10.on()方法
$(selector).on(event,childSelector,data,function,map)
11.模拟触发事件
我们可以通过trigger模拟触发一个click事件
var press = $("#press");press.on("click",function(e, how){how = how || "";alert("The buton was clicked " + how + "!");});press.trigger("click");press.trigger("click",["fast"]);同时,我们亦可以,使用on()方法创建自己喜欢的事件名称,然后通过trigger来触发。举例如下:
<button id="button1">Jump</button> <button id="button2">Punch</button> <button id="button3">Click</button> <button id="clear" style="float: right;">Clear</button> <div id="eventDiv"></div>
var button1 = $("#button1"),button2 = $("#button2"),button3 = $("#button3"),clear = $("#clear"),div = $("#eventDiv");div.on({jump : function(){alert("Jumped!");},punch : function(e,data){alert("Punched "+data+"!");},click : function(){alert("Simulated click!");}});button1.click(function(){div.trigger("jump");});button2.click(function(){// Pass data along with the eventdiv.trigger("punch",["hard"]);});button3.click(function(){div.trigger("click");});clear.click(function(){//some clear code});12.触摸事件
// Define some variablesvar ball = $("<div id="ball"></div>").appendTo("body"),startPosition = {}, elementPosition = {};// Listen for mouse and touch eventsball.on("mousedown touchstart",function(e){e.preventDefault();// Normalizing the touch event objecte = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;// Recording current positionsstartPosition = {x: e.pageX, y: e.pageY};elementPosition = {x: ball.offset().left, y: ball.offset().top};// These event listeners will be removed laterball.on("mousemove.rem touchmove.rem",function(e){e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;ball.css({top:elementPosition.y + (e.pageY - startPosition.y),left: elementPosition.x + (e.pageX - startPosition.x),});});});ball.on("mouseup touchend",function(){// Removing the heavy *move listenersball.off(".rem");});13.更快的阻止默认事件
<a href="http://google.com/" id="goToGoogle">Go To Google</a>
$("#goToGoogle").click(false);14.使用event.result链接多个事件处理程序。
var press = $("#press");press.on("click",function(){return "Hip";});press.on("click",function(e){console.log(e.result + " Hop!");})//控制台输出: HipHop!15.平行的运行多个Ajax请求
$.when($.get("assets/misc/1.json"), $.get("assets/misc/2.json")).then(function(r1, r2){console.log(r1[0].message + " " + r2[0].message);})16.通过jQuery获得ip
$.get("https://jsonip.com/", function(res){ console.log(res.ip); });
<p class="content"></p> <p class="content"></p>
var contentDivs = $(".content");contentDivs.eq(0).load("1.txt");contentDivs.eq(1).load("1.html #header");18.通过IP地址获得地理位置
var ip = "119.75.218.70",api = "http://freegeoip.net/json/" + ip + "?callback=?";$.getJSON(api, function(r){console.log("How is the weather in " + r.city + ", " + r.country_name + "?");});19.使用匿名函数来产生一个独立的代码块
(function($){var c = 1;$.fn.count = function(){log(c++);return this;}; })(jQuery);$(document).count();$("body").count().count();以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!