Home Web Front-end JS Tutorial Share javascript and jquery practical code snippets

Share javascript and jquery practical code snippets

Dec 09, 2016 pm 03:05 PM

The example in this article is to simply share the practical demo of javascript and jquery for your reference. The specific content is as follows

javascript determines whether the H5 page has left

1

2

3

4

5

6

7

8

9

10

11

12

13

14

function onbeforeunloadFn(){

 console.log('离开页面');

 //...code

}

function showOnbeforeunload(flags){

 if(flags){

 document.body.onbeforeunload = onbeforeunloadFn;

 }else{

 document.body.onbeforeunload = null;

 }

}

$(function(){

 showOnbeforeunload(true);

})

Copy after login

jq determines whether the img tag image address has been loaded

1

2

3

4

5

6

imgStatus = 0;

 $("img").each(function(){

 if(this.complete){/*this.complete代表图片加载完成*/

  imgStatus++;

 }

 });

Copy after login

iframe gets content-and settings

1

2

3

4

5

6

7

if($(".ad_show iframe").size() > 0 ){

 $(".ad_show iframe").attr("id","iframead");/*设置iframe的id*/

 /*获取id为iframead的iframe的dom对象*/

 var iframebox = document.getElementById("iframead").contentWindow;

 /*设置兜底内容*/

 iframebox.document.body.innerText = "1234";

}

Copy after login

javascript gets the url of the previous page in the browser

1

2

/*返回上一次url,如果是新窗口则不能获取到*/

var beforeUrl = document.referrer;

Copy after login

About the headache-inducing mobile click bubble event

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

<script>

$(".class").live(&#39;tap&#39;,function(oEvent){

 e = window.event || oEvent;

 if(e.stopPropagation){

 e.stopPropagation();

 }else{

 e.cancelBubble = true;

 }

 e.preventDefault();

});

</script>

/*虽说tap事件可以阻止大部分冒泡事件,但是还是有一小部分移动端不吃你这套,那么有另外一个解决办法*/

/*将层级间的事件通过H5属性data-flag="true"来控制*/

<!--html-->

<div class="parentTap" data-flag="true">

 <div class="childTap" data-flag="false">

 <div class="childsTap" data-flag="false">

  ....

 </div>

 </div>

</div>

<!--给父级parentTap绑定一个点击事件-->

<!--给子级childTap绑定一个点击事件-->

<!--给子孙级childsTap绑定一个点击事件-->

<script type="text/javascript">

 var bindInit = function(className){

 if($(className).size() > 0){

  $(className).on(&#39;tap&#39;,function(oEvent){

  e = window.event || oEvent;if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble = true;}e.preventDefault();

  var flag = $(this).data(&#39;flag&#39;);

  if(flag){/*为true时允许点击进入事件*/

   /* code... */

  }

  });

 }

 }

 $(function(){

 bindInit(&#39;.parentTap&#39;);

 bindInit(&#39;.childTap&#39;);

 bindInit(&#39;.childsTap&#39;);

 });

</script>

Copy after login

Simple countdown function

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

<div class="newTime" data-end="2016-10-13 23:59:59" data-now="2016-10-13 03:59:59">

 <div class="t_d"></div>

 <div class="t_h"></div>

 <div class="t_m"></div>

 <div class="t_s"></div>

</div>

 <script type="text/javascript">

 /*倒计时*/

 var timeDown = {

  GetRTime: function (timeId,oldNowTime) {

  var tempTime;/*保存上一次时间*/

  if(oldNowTime){

   tempTime = new Date(oldNowTime.getTime() + 1000);/*如果有上一次时间则赋值*/

   /*console.log(tempTime);*/

  }

  var EndTime = new Date($("#" + timeId).data("end"));/*获取结束时间*/

  if (!tempTime) {

   if ($("#" + timeId).data("now") == "" || $("#" + timeId).data("now") == "null") {

   var NowTime = new Date();

   } else {

   var NowTime = new Date($("#" + timeId).data("now"));/*取开始时间*/

   }

  } else {

   var NowTime = tempTime;

  }

  if (EndTime.getTime() >= NowTime.getTime()) {/*判断时间*/

   var t = EndTime.getTime() - NowTime.getTime();/*得到结束时间减去开始时间的时间戳*/

   var d = Math.floor(t / 1000 / 60 / 60 / 24);/*日*/

   var h = Math.floor(t / 1000 / 60 / 60 % 24);/*时*/

   var m = Math.floor(t / 1000 / 60 % 60);/*分*/

   var s = Math.floor(t / 1000 % 60);/*秒*/

   /*将时间填入对应的html中*/

   $(".t_d", "#" + timeId).html((d > 9 ? &#39;&#39; : &#39;0&#39;) + d);

   $(".t_h", "#" + timeId).html((h > 9 ? &#39;&#39; : &#39;0&#39;) + h);

   $(".t_m", "#" + timeId).html((m > 9 ? &#39;&#39; : &#39;0&#39;) + m);

   $(".t_s", "#" + timeId).html((s > 9 ? &#39;&#39; : &#39;0&#39;) + s);

   tempTime = new Date(NowTime.getTime() + 1000);/*将开始时间+1秒*/

   setTimeout(function () {

   timeDown.GetRTime(timeId,NowTime);/*等待一秒后继续执行*/

   }, 1000);

  } else if (EndTime.getTime() == NowTime.getTime()) {/*当时间相等时要做处理的code*/

   $("#"+timeId).hide();

  }

  }

 }

 var t=0;

 if ($(".newTime").size() > 0) {

  $(".newTime").each(function(){

  var timeId="timeOut"+t;

  $(this).attr("id",timeId);/*设置多个倒计时时指定唯一id*/

  t++;

  timeDown.GetRTime(timeId,null);/*开始调用*/

  });

 }

 </script>

Copy after login

jQuery’s node operation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

jQuery.parent(expr) /*找父亲节点,可以传入expr进行过滤,比如$("span").parent()或者$("span").parent(".class")*/

  

jQuery.parents(expr) /*类似于jQuery.parents(expr),但是是查找所有祖先元素,不限于父元素*/

  

jQuery.children(expr) /*返回所有子节点,这个方法只会返回直接的孩子节点,不会返回所有的子孙节点*/

  

jQuery.contents() /*返回下面的所有内容,包括节点和文本。这个方法和children()的区别就在于,包括空白文本,也会被作为一个*/

  

/*

 jQuery对象返回,children()则只会返回节点

  

 jQuery.prev(),返回上一个兄弟节点,不是所有的兄弟节点

  

 jQuery.prevAll(),返回所有之前的兄弟节点

  

 jQuery.next(),返回下一个兄弟节点,不是所有的兄弟节点

  

 jQuery.nextAll(),返回所有之后的兄弟节点

  

 jQuery.siblings(),返回兄弟姐妹节点,不分前后

  

 jQuery.find(expr),跟jQuery.filter(expr)完全不一样。

 jQuery.filter()是从初始的jQuery对象集合中筛选出一部分,

 而jQuery.find()的返回结果,不会有初始集合中的内容,

 比如$("p"),find("span"),是从<p>元素开始找<span>,等同于$("p span")

*/

Copy after login

The in syntax in the if judgment statement in js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/*

在js代码中

通常的if判断语句会这样写:

*/

if(1 == 1){

 alert("1等于1");

}else{

 alert("1不等于1");

}

/*而在in写法下可以这样:*/

if(1 in window){

 alert("window包含1");

}else{

 alert("window不包含1");

}

Copy after login

js try-catch

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

try{

 foo.bar();

}catch(e){

 console.log(e.name + ":" + e.message);

}

try{

 throw new Error("Whoops!");

}catch(e){

 console.log(e.name + ":" + e.message);

}

/*

改js代码会捕获一个异常错误:

 因为foo.bar();是未定义的;

 因此在js代码中如果没有异常捕获,整个页面都不会继续解析.

 从而导致页面加载失败.

 这里就需要通过try-catch来异常捕获这种错误,并把他反馈出来

  

目前我们可能得到的系统异常主要包含以下6种:

 EvalError: raised when an error occurs executing code in eval()

 翻译:当一个错误发生在eval()执行代码

 RangeError: raised when a numeric variable or parameter is outside of its valid range

 翻译:当一个数值变量或参数的有效范围之外

 ReferenceError: raised when de-referencing an invalid reference

 翻译:引用无效的引用

 SyntaxError: raised when a syntax error occurs while parsing code in eval()

 翻译:语法错误,当发生语法错误在eval()解析代码里

 TypeError: raised when a variable or parameter is not a valid type

 翻译:错误类型:当一个变量或参数不是一个有效的类型

 URIError: raised when encodeURI() or decodeURI() are passed invalid parameters

 翻译:调用encodeURI()或decodeURI()时,传入的参数是不通过无效的

  

以下是异常捕获是的属性:

 Error具有下面一些主要属性:

 description: 错误描述 (仅IE可用).

 fileName: 出错的文件名 (仅Mozilla可用).

 lineNumber: 出错的行数 (仅Mozilla可用).

 message: 错误信息 (在IE下同description)

 name: 错误类型.

 number: 错误代码 (仅IE可用).

 stack: 像Java中的Stack Trace一样的错误堆栈信息 (仅Mozilla可用).

*/

/*

 如要判断异常信息的类型,可在catch中进行判断:

 */

  

try {

 coo.bar();//捕获异常,ReferenceError:引用无效的引用

}catch(e){

 console.log(e instanceof EvalError);

 console.log(e instanceof RangeError);

 if(e instanceof EvalError){

 console.log(e.name + ":" + e.message);

 }else if(e instanceof RangeError){

 console.log(e.name + ":" + e.message);

 }else if(e instanceof ReferenceError){

 console.log(e.name + ":" + e.message);

 }

}

Copy after login

typeof and instanceof difference

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

/*先捕获异常,抛出异常*/

try {

 throw new myBlur(); // 抛出当前对象

}catch(e){

 console.log(typeof(e.a)); //返回function类型

 if(e.a instanceof Function){//instanceof用于判断一个变量是否某个对象的实例,true

 console.log("是一个function方法");

 e.a();//执行这个方法,输出"失去焦点"

 }else{

 console.log("不是一个function方法");

 }

}

function myBlur(){

 this.a = function(){

 console.log("失去焦点");

 };

}

  

/*

 通畅typeof一般只能返回如下几个结果:

 number,boolean,string,function,object,undefined;

 如果要用if做比较则比较后面要用双引号引起来

*/

 if(typeof(param) == "object"){

 alert("该参数等于object类型");

 }else{

 alert("该参数不等于object类型");

 }

  

/*又如:*/

console.log(Object instanceof Object);//true

console.log(Function instanceof Function);//true

console.log(Number instanceof Number);//false

console.log(String instanceof String);//false

console.log(Function instanceof Object);//true

console.log(Foo instanceof Function);//true

console.log(Foo instanceof Foo);//false

Copy after login

HTML5 cache sessionStorage

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

sessionStorage.getItem(key)//获取指定key本地存储的值

sessionStorage.setItem(key,value)//将value存储到key字段

sessionStorage.removeItem(key)//删除指定key本地存储的值

sessionStorage.length//sessionStorage的项目数

  

/*

sessionStorage与localStorage的异同:

 sessionStorage和localStorage就一个不同的地方,

 sessionStorage数据的存储仅特定于某个会话中,

 也就是说数据只保持到浏览器关闭,当浏览器关闭后重新打开这个页面时,之前的存储已经被清除。

 而localStorage是一个持久化的存储,它并不局限于会话

  

sessionStorage和localStorage的clear()函数的用于清空同源的本地存储数据:

 比如localStorage.clear(),它将删除所有同源的本地存储的localStorage数据,

 而对于SessionStorage,它只清空当前会话存储的数据。

  

sessionStorage和localStorage具有相同的方法storage事件:

 在存储事件的处理函数中是不能取消这个存储动作的。

 存储事件只是浏览器在数据变化发生之后给你的一个通知。

 当setItem(),removeItem()或者clear() 方法被调用,

 并且数据真的发生了改变时,storage事件就会被触发。

 注意这里的的条件是数据真的发生了变化。也就是说,

 如果当前的存储区域是空的,你再去调用clear()是不会触发事件的。

 或者你通过setItem()来设置一个与现有值相同的值,事件也是不会触发的。

 当存储区域发生改变时就会被触发。

*/

Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles