本来以为js和Python特别像,那么Python的这种默认参数也可以
function createDom(type, attrN = "null", attrV = "null", attr2N = 'null', attr2V = 'null'){
var self = document.createElement(type);
if(attrN != "null") {
self.setAttribute(attrN,attrV);
if(attr2N != "null"){
self.setAttribute(attr2N,attr2V);
}
}
return self;
}
这样写,chrome是可以运行的。但是ie不行。后来网上查了下,可以使用arguments实现
//方法1
function createDom(){
var type = arguments[0] ? arguments[0] : 'null';
var attrN = arguments[1] ? arguments[1] : 'null';
var attrV = arguments[2] ? arguments[2] : 'null';
var attr2N = arguments[3] ? arguments[3] : 'null';
var attr2V = arguments[4] ? arguments[4] : 'null';
var self = document.createElement(type);
if(attrN != "null") {
self.setAttribute(attrN,attrV);
if(attr2N != "null"){
self.setAttribute(attr2N,attr2V);
}
}
也可以是这样
//方法2
function createDom(type, attrN , attrV, attr2N, attr2V){
type = type ? type : 'null';
attrN = attrN ? attrN : 'null';
attrV = attrV ? attrV : 'null';
attr2N = attr2N ? attr2N : 'null';
attr2V = attr2V ? attr2V : 'null';
var self = document.createElement(type);
if(attrN != "null") {
self.setAttribute(attrN,attrV);
if(attr2N != "null"){
self.setAttribute(attr2N,attr2V);
}
}
return self;
}
或者这样(推荐)
//方法3
function createDom(type, attrN , attrV, attr2N, attr2V){
type = type || 'null';
attrN = attrN || 'null';
attrV = attrV || 'null';
attr2N = attr2N || 'null';
attr2V = attr2V || 'null';
var self = document.createElement(type);
if(attrN != "null") {
self.setAttribute(attrN,attrV);
if(attr2N != "null"){
self.setAttribute(attr2N,attr2V);
}
}
return self;
}