我正在动态添加输入字段以及允许用户删除此字段的“x”。看起来像 this
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' })
关于javascript - 将类添加到 javascript 创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42124514/