gpt4 book ai didi

jquery - 使用 jQuery 即时创建标签

转载 作者:行者123 更新时间:2023-12-03 22:00:34 25 4
gpt4 key购买 nike

我需要动态创建标签和文本字段,并且还包括文本字段的日期选择器。我需要这样的东西:

<label for="from">From </label> <input type="text" id="from" name="from" />

我在 jQuery 中尝试过类似的方法:

var label = $("<label>").attr('for', "from");   
label.html('Date: ' +
'<input type="text" id="from name="from" value="">');

$(function() {
$("#from").datepicker();
});

这个以某种方式不会创建标签和文本字段。我不确定我错过了什么。

编辑

更准确地说,我在 portlet 中使用它,并且在 jsp 页面中没有 body 标记。因此,当我调用函数附加到正文时,它不会。

最佳答案

像这样的东西会起作用:

//Create the label element
var $label = $("<label>").text('Date:');
//Create the input element
var $input = $('<input type="text">').attr({id: 'from', name: 'from'});

//Insert the input into the label
$input.appendTo($label);
//Insert the label into the DOM - replace body with the required position
$('body').append($label);

//applying datepicker on input
input.datepicker();

jsFiddle Demo

请注意,如果输入元素位于标签内,则不必在标签上使用 for 属性。因此,请使用其中之一:

<label><input id="x1"></label>

<label for="x1"></label> <input id="x1">

关于jquery - 使用 jQuery 即时创建标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10401034/

25 4 0