tôi đã nhanh chóng thực hiện một chức năng mà có thể đạt được điều này, nó có thể không phải là cách tốt nhất để làm điều này nhưng nó chỉ đơn giản là hoạt động và nên được qua trình duyệt, xin vui lòng cũng biết rằng tôi KHÔNG phải là một chuyên gia trong JavaScript vì vậy bất kỳ lời khuyên là tuyệt vời :)
Pure Javascript Tạo phần tử Giải pháp
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
cho phép xem cách chúng tôi làm cho điều này
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
dưới đây là cách nó hoạt động
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
đây là params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
Chức năng này sẽ phù hợp với nếu bạn phải ap nhiều yếu tố, nếu có bất kỳ cách nào để cải thiện câu trả lời này xin vui lòng cho tôi biết.
chỉnh sửa:
Đây là một bản demo làm việc
này có thể được tùy biến rất cao cho phù hợp với dự án của bạn!
Nhìn vào 'document.createElement' và' element.appendChild' – Ian
@koukouloforos là câu trả lời của tôi là hữu ích không? – WooCaSh
@WooCaSh nó làm những gì tôi đang yêu cầu nhưng tôi thích nếu một cái gì đó trong javascript đơn giản. –