Adding parameters to function
This question already has an answer here:
You're getting an error because a space is not a valid character in a class name. Instead pass individual strings, and receive them as a rest parameter.
Then you can use spread syntax to pass the list of classes to classList.add()
.
// Receive all the classes--------v
function Img(imgId, imgSrc, ...imgClass) {
this.imgId = imgId || '';
this.imgSrc = imgSrc || '';
this.imgClass = imgClass;
let elm = document.createElement('img');
//elm.setAttribute('id', this.imgId);
//elm.setAttribute('src', this.imgSrc);
// This is shorter than using `.setAttribute()`
elm.id = this.imgId;
elm.src = this.imgSrc;
elm.classList.add(...this.imgClass); // Add all the classes
var xyz = document.getElementById('xyz');
this.createImage = function() {
xyz.appendChild(elm);
}
}
var flowerImg = new Img('flower', 'http://via.placeholder.com/350x150', 'img').createImage();
var airplane = new Img('airplane', 'http://via.placeholder.com/350x150', 'img', 'img-wide').createImage();
<div action="" id="xyz">
</div>
您需要将这些类拆分为单独的字符串并分别应用每个字符串
function Img(imgId, imgSrc, imgClass) {
this.imgId = imgId || '';
this.imgSrc = imgSrc || '';
this.imgClass = imgClass;
let elm = document.createElement('img');
elm.setAttribute('id', this.imgId);
elm.setAttribute('src', this.imgSrc);
this.imgClass.split(' ').forEach(function(singleClass) {
elm.classList.add(singleClass);
})
var xyz = document.getElementById('xyz');
this.createImage = function() {
xyz.appendChild(elm);
}
}
var flowerImg = new Img('flower', 'http://via.placeholder.com/350x150', 'img').createImage();
var airplane = new Img('airplane', 'http://via.placeholder.com/350x150', 'img img-wide').createImage();
<div action="" id="xyz">
</div>
Just use the .className
property. There you can set multiple classes at once.
For example:
elm.className = this.imgClass;
Or if there is already a class defined for the element just use it with the +
operator, but be aware that you have to insert a space as separator:
elm.className += " " + this.imgClass;
链接地址: http://www.djcxy.com/p/25226.html
上一篇: “git reset”和“git checkout”有什么区别?
下一篇: 将参数添加到功能