[英]Adding class to javascript created element
我正在動態添加輸入字段以及允許用戶刪除此字段的“x”。 看起來像這樣
Javascript 看起來像這樣:
$(document).ready(function() {
// When the add_button is pressed
$('#add_correct_answer').click(function() {
// Container (already created)
var container = $('.buttons-fields-correct');
// Create the input wrapper (input tag + delete button), and append it to `container`
var input_wrapper = $('<div>', { class: 'input-wrapper' }).appendTo(container);
// Create an input tag, and append it to input_wrapper
var input = $('<input>', { name: 'task[correct_answers][]', type: 'text' }).appendTo(input_wrapper);
// Create the remove button, append it to input_wrapper, and add a click callback to
// remove the input wrapper if it's pressed.
var remove = $('<span>', { text: 'x' }).appendTo(input_wrapper).click(function() {
input_wrapper.remove();
});
});
相關 HTML:
<%= label :form_type, t(:add_correct_answers) %>
<div class="buttons-wrapper">
<%= button_tag t(:add_field), id: 'add_correct_answer', type: 'button' %>
<div class="buttons-fields-correct">
<div>
</div>
</div>
</div>
我想要做的是給這個“x”一個類,我可以修改和改變這個“x”的外觀/位置。 例如將其放置在右側的輸入內。
您可以在定義元素類型時添加它,也可以像添加text
一樣添加class
屬性。
所以
$('<span class="some-class">', { text: 'x' })
或者
$('<span>', { text: 'x', class:'some-class' })
var remove = $('<span>', { text: 'x' }).addClass('your-class').appendTo(input_wrapper).click(function() {
input_wrapper.remove();
要么按照 Gaby 的建議做,要么在創建 span 后給它一個類名:
document.(getElementInSomeWay).setAttribute("class", "democlass"); = "myClass";
或在 Jquery 中:
$('<span>').addClass('myClass');
我建議您在單獨的 css 文件或一些預處理器中制作外觀。 然后應用具有特定位置坐標的類
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.