JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。
本文为大家整理了5段实用JavaScript代码,便于大家进行开发。
1. 判断日期是否有效
JavaScript中自带的日期函数还是太过简单,很难满足真实项目中对不同日期格式进行解析和判断的需要。JQuery也有一些第三方库来使日期相关的处理变得简单,但有时你可能只需要一个非常简单的函数,而不想引入一个庞大的第三方库。这时,你可以使用下面这段日期校验代码,它允许你自定义日期格式并进行日期有效性的校验。
function isValidDate(value, userFormat) { // Set default format if format is not provided userFormat = userFormat || 'mm/dd/yyyy'; // Find custom delimiter by excluding // month, day and year characters var delimiter = /[^mdy]/.exec(userFormat)[0]; // Create an array with month, day and year // so we know the format order by index var theFormat = userFormat.split(delimiter); // Create array from user date var theDate = value.split(delimiter); function isDate(date, format) { var m, d, y, i = 0, len = format.length, f; for (i; i < len; i++) { f = format[i]; if (/m/.test(f)) m = date[i]; if (/d/.test(f)) d = date[i]; if (/y/.test(f)) y = date[i]; } return ( m > 0 && m < 13 && y && y.length === 4 && d > 0 && // Check if it's a valid day of the month d <= (new Date(y, m, 0)).getDate() ); } return isDate(theDate, theFormat);}
使用方法:
下面这个调用返回false,因为11月份没有31天
isValidDate('dd-mm-yyyy', '31/11/2012')
2. 获取一组元素的最大宽度或高度
下面这个函数,对于需要进行动态排版的开发人员非常有用。
var getMaxHeight = function ($elms) { var maxHeight = 0; $elms.each(function () { // In some cases you may want to use outerHeight() instead var height = $(this).height(); if (height > maxHeight) { maxHeight = height; } }); return maxHeight;};
使用方法:
$(elements).height( getMaxHeight($(elements)) );
3. 高亮文本
有很多JQuery的第三方库可以实现高亮文本的功能,但我更喜欢用下面这一小段JavaScript代码来实现这个功能,它非常短小,而且可以根据我的需要去进行灵活的修改,而且可以自己定义高亮的样式。下面这两个函数可以帮助你创建自己的文本高亮插件。
function highlight(text, words, tag) { // Default tag if no tag is provided tag = tag || 'span'; var i, len = words.length, re; for (i = 0; i < len; i++) { // Global regex to highlight all matches re = new RegExp(words[i], 'g'); if (re.test(text)) { text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>'); } } return text;}
新闻热点
疑难解答
图片精选