如何在JS中使用属性创建元素? 我正在尝试在JavaScript中创建音频标签。 我有以下 this.audioElement = createElement('audio',{className:'audio',src:'test.mp3',type:'audio/mpeg'}); 我想ap的音频标签...

问题描述 投票:0回答:5
中的音频标签

this.audioElement = createElement('audio', {className:'audio', src:'test.mp3', type:'audio/mpeg'});

我不确定如何在JS中创建
<audio controls src='test.mp3' type='audio/mpeg'></audio>

属性。谁能帮我吗?

现在got

controls

                
为了工作,您需要一个辅助功能

this.audioElement = createElement('audio', {className:'audio-asset', src:'test.mp3'}); this.audioElement.setAttribute('controls',true);

有点像这样的工作:

createElement
javascript html
5个回答
7
投票
现在您可以做:

var createElement = function(type, props) { var $e = document.createElement(type); for (var prop in props) { $e.setAttribute(prop, props[prop]); } return $e; }
    

4
投票
上面的答案似乎对我不起作用。这是我所做的:

this.audioElement = createElement('audio', {className:'audio', src:'test.mp3', type:'audio/mpeg', controls: true});
the inden chite chepthe:

var audioElement;
audioElement = document.createElement('audio');
audioElement.setAttribute('controls', true);
audioElement.setAttribute('class', 'audio');
audioElement.setAttribute('src', 'test.mp3');
audioElement.setAttribute('type', 'audio/mpeg');

audioElement

3
投票
为boolean属性,例如

document.body.appendChild(audioElement);

var audioElement = document.createElement('audio');

//your own code for setting the attributes you have already set

audioElement.controls=true;
将它们设置为

multiple

从@megawac和詹姆斯的答案开始,我认为在
现代浏览器上的多个属性的最清洁方法可能使用对象。
disabled

0
投票
不仅是一个函数呼叫,而是比这里的一些较旧的答案可读和详细。

我很熟悉与jQuery这样做。  没有jQuery,我不知道该怎么做。

true

    
可启用控制

html
const colInput = document.createElement('input');
Object.assign(colInput,{
    type: 'number',
    min: 1,
    value: this.config.cols,
    onchange: this.updateSetting
});


0
投票

var $el = $('<audio>', { class: 'audio', src: 'test.mp3', type: 'audio/mpeg', controls: 'controls goes here' }); var html = $el[0].outerHTML;

© www.soinside.com 2019 - 2025. All rights reserved.