Javascript Tips

另一篇博客,记录jQuery的操作:jQuery Tips

 

2. appendChild(newChild),例:oParentNode.appendChild(newElement);

4. 检测jquery是否加载

window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}

6. document.forms[""] 得到当前document的某个form,document.forms得到的是当天document中所有form的集合,详见W3school

7. JS注释

单行:
// document.getElementById("");

多行:

/*
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
*/

 

8. XML中的冒号需要转义,例如,z:row要写成z\\:row才能进行查找,例如:

    $(xData.responseXML).find('z\\:row').each(function(){});

9. 要查看ajax返回的数据,直接使用xml属性即可,例如:alert(xData.responseXML.xml);

11. JavaScript中可以直接将一个函数(function)赋给一个变量;

//先创建一个函数
function
retrieveWebsite(resultpanel) { var clientContext; clientContext = SP.ClientContext.get_current(); this.oWebsite = clientContext.get_web(); clientContext.load(this.oWebsite); clientContext.executeQueryAsync( Function.createDelegate(this, successHandler), Function.createDelegate(this, errorHandler) ); function successHandler(sernder, args) { resultpanel.innerHTML = "Web site title: " + this.oWebsite.get_title(); } function errorHandler(sender, args) { resultpanel.innerHTML = "Request failed: " + args.get_message();//arguments[1] } }
//在另外一个JS文件中需要用到这个函数时,可以直接将函数赋给变量,
var func = window[funcName];
//然后进行调用 func($(
"#" + this.parentElement.id + " .result-panel")[0]);

12. 实现类似博客园中的在页面显示代码块的功能:

HTML:

<a href="#" class="code-link">View code</a><br />
<div class="code-content"></div>

CSS:

.code-content
{
    display : none;
    font-family : Consolas;
    top : -3px;
    clear : both;
    border-color : #e5e5e5;
    border-width : 1px;
    border-style : solid;
    position : relative;
    padding : 5px;
    margin : 10px;
}

Javascript:

$("a.code-link").click(function () {
    $("#" + this.parentElement.id + " .code-content").toggle();

    if ($("#" + this.parentElement.id + " .code-content").is(":visible")) {
        var funcName;
        var funcText;

        funcName = this.parentElement.id.replace("Container", "");
        funcText = window[funcName].toString();
        funcText = $("<div></div>").text(funcText).html();
        alert(funcText);
        funcText = funcText.replace(/\r\n/g, "<br/>");
        funcText = funcText.replace(/ /g, "&nbsp;");
        alert(funcText);
        $("#" + this.parentElement.id + " .code-content").html(funcText)
    }
});

13. 正则表达式中的斜杠标识了表达式的前后位置:

语法:

var patt = new RegExp(pattern,modifiers);

or more simply:

var patt = /pattern/modifiers;

14. 在HTML中,单引号被转义为&#39; 双引号为&quot;

15. appendChild是HTML DOM的方法,append是jQuery方法,append可以确保每次添加的元素都放在末尾;

16. 使用以下代码判断变量是否为null

以下是正确的用法:
var exp = null;
if (!exp && typeof(exp)!="undefined" && exp!=0)
{
    alert("is null");
} 
尽管如此,我们在DOM应用中,一般只需要用 (!exp) 来判断就可以了,因为 DOM 应用中,可能返回 null,可能返回 undefined,如果具体判断 null 还是 undefined 会使程序过于复杂

17. setInterval对应clearInterval,setTimeout对应clearTimeout;

var timer;
$('#result').text('waiting…');
  var promise = process();
promise.done(function() {
  $('#result').html('done.');
});
promise.progress(function(parameters) {
  $('#result').html($('#result').html() + '.');
    $("#result2").html($("#result2").html() + parameters + ' ');
    document.body.style.backgroundColor=document.body.style.backgroundColor=="yellow"?"pink":"yellow";
});
 
function process() {
  var deferred = $.Deferred();
 
  timer = setInterval(function(parameters) {
    deferred.notify(parameters);
  }, 1000, 'ABC');
   
  setTimeout(function() {
     clearInterval(timer);
     deferred.resolve();
  }, 10000);
   
  return deferred.promise();
}
View Code

另外,setInterval是每隔多久执行一次,而setTimeout是等待多久之后执行一次;在setInterval和setTimeout中调用函数时,需要用以下方法调用,不能直接将方法写在第一个参数的位置:

setInterval(function(){ myFunction() }, 1000); // 正确写法
setInterval(myFunction(), 1000); //错误写法,不会执行此方法

18. Date对象 - 使用以下方法新建一个Date对象:

var selectedDateObj=new Date(dateStr); //此处的dateStr可以是多种格式,比如:2015-05-02,也可以是05/02/2015等

使用以下方法可以从Date对象中获取当前的年月日信息:

var year=date.getFullYear();
var month=date.getMonth()+1;
var day=date.getDate();

使用一下方法为为Date对象增加month;

    //Add months to a date
       function addMonths(dateObj, num){
            var currentMonth = dateObj.getMonth() + dateObj.getFullYear() * 12;
            dateObj.setMonth(dateObj.getMonth() + num);
            var diff = dateObj.getMonth() + dateObj.getFullYear() * 12 - currentMonth;
        
            // If don't get the right number, set date to 
            // last day of previous month
            if (diff != num) {
                dateObj.setDate(0);
            } 
            return dateObj;
        }

19. JavaScript 数组定义方式有多钟,而且向二维数据中添加数据时,push方法后的括号中添加一个新的数组时,不需要再使用new Array(["A","B"]),直接写push(["A","B"]);

var peopleArray = new Array();
//或者
var peopleNameArray = [];


//添加内容时
peopleArray.push("A"); //表明此处为普通数组
peopleNameArray.push(["A", "B"]); //表明此处为2维数组

20. JavaScript中实现类似C#中Format字符串的方法:

String.format = function() {
            // The string containing the format items (e.g. "{0}")
            // will and always has to be the first argument.
            var theString = arguments[0];
            
            // start with the second argument (i = 1)
            for (var i = 1; i < arguments.length; i++) {
                // "gm" = RegEx options for Global search (more than one instance)
                // and for Multiline search
                var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
                theString = theString.replace(regEx, arguments[i]);
            }
            return theString;
        }
调用方法:
// http://joQuery.com/2012/string-format-for-javascript
    var url = 'http://joquery.com',
        year = 2012,
        titleEncoded = 'string-format-for-javascript',
        title = 'string.format for Javascript';
    
    var link = String.format('<a href="{0}/{1}/{2}" title="{3}">{3}</a>',
                             url, year, titleEncoded, title);

21. 在HTML控件事件中调用javascript函数时,不能只写方法名,需要加上括号,例如 onclick="doSomething()";

22. location.reload() 重新加载当前页面;

23. replace()函数不仅可以使用字符串来进行匹配,还可以使用正则表达式来进行匹配;

注:两个斜杠(/)之间的部分标识着子字符串或要替换的模式的 RegExp 对象;

<script type="text/javascript">

var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))

  var startDateTime = "2015/12/8";
  startDateTime = startDate.replace(/\//g,"-")+"T00:00:00Z";

</script>

24. 在 JavaScript中使用 类(Class):

$(document).ready(function () {
    //define NameSpace
    window.CustomNameSpaceA = window.CustomNameSpaceA || {};

    //define Class
    CustomNameSpaceA.CalculationClass = function (numberA, numberB) {
        if (isNumber(numberA)) {
            this.numberA = numberA;
        }
        else {
            this.numberA = 0;
        }

        if (isNumber(numberB)) {
            this.numberB = numberB;
        }
        else {
            this.numberB = 1;
        }
    }

    //Prototype
    CustomNameSpaceA.CalculationClass.prototype = {
        init: function () {
            if (this.numberA < 10) {
                this.numberA = 10;
            }

            if (this.numberB < 2) {
                this.numberB = 2;
            }

            this.showItems();
        },

        showItems: function () {
            var result = this.numberA + this.numberB;
            $("#displayDiv").text(result);
        }
    }

    //invoke custom class
    function getCalculationResults() {
        var calClassInstance = new CustomNameSpaceA.CalculationClass(2, 1);
        calClassInstance.init();
    }
});

//run
getCalculationResults();

25. decodeURIComponent()方法用于对编码后的URI进行解码,对应的encodeURIComponent()是用于对URI进行编码:

<script type="text/javascript">

var test1="http://www.w3school.com.cn/My first/"

document.write(encodeURIComponent(test1)+ "<br />")
document.write(decodeURIComponent(test1))

</script>

输出为:

http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F
http://www.w3school.com.cn/My first/

26. 对字符串数组进行排序时需要注意两点:(1)是sort()方法默认是大小写敏感的,因此需要自己写一个排序方法(示例如下),(2)是 sort()方法的结果会影响到当前数组,所以无需新建数组来存储排序后的数据;

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "thomas"
arr[3] = "james"
arr[4] = "Adrew"
arr[5] = "Martin"

arr.sort (function(a,b){
  return a.toLowerCase().localeCompare(b.toLowerCase());
});

document.write(arr + "<br />");

27. Object.keys() 会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组,详情请参考此页面

var person = {
                    name: "xxx",
                    website: "http://xxx.com",
                    twitter: "@xxx"
                };

                var keys = Object.keys(person);
                // keys 值为 ['name', 'website', 'twitter']

28. JavaScript中的split方法默认不提供忽略空值的方法,但可以自己添加一个方法实现,参考此页

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {         
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);

29. 

 

 

posted @ 2014-03-19 13:20  Jacky Ge  阅读(705)  评论(0编辑  收藏  举报