使用 jQuery 即时创建标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10401034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a label using jQuery on the fly
提问by user525146
I need to create a label and text field on the fly and also include datepicker for the textfield. I need something like this:
我需要动态创建一个标签和文本字段,还需要为文本字段包含日期选择器。我需要这样的东西:
<label for="from">From </label> <input type="text" id="from" name="from" />
I have tried something like this in jQuery:
我在 jQuery 中尝试过这样的事情:
var label = $("<label>").attr('for', "from");
label.html('Date: ' +
'<input type="text" id="from name="from" value="">');
$(function() {
$("#from").datepicker();
});
This one somehow doesn't create the label and also the text field. I am not sure what I am missing.
这个不知何故不会创建标签和文本字段。我不确定我错过了什么。
EDIT
编辑
To be more precise, I am using this in the portlets and I don't have body tags in the jsp page. So when I call the function to append to body it won't.
更准确地说,我在 portlet 中使用它,并且在 jsp 页面中没有 body 标记。所以当我调用函数附加到 body 时,它不会。
回答by kapa
Something like this would work:
像这样的事情会起作用:
//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();
Please note that you don't have to use the for
attribute on the label if the input element is inside it. So use one of these:
请注意,for
如果 input 元素在其中,则不必在标签上使用该属性。所以使用以下之一:
<label><input id="x1"></label>
<label for="x1"></label> <input id="x1">
回答by rjz
You will need to attach the label you've created to the DOM to get it to show:
您需要将您创建的标签附加到 DOM 以使其显示:
var label = $("<label>").attr('for', "from");
label.html('Date: ' +
'<input type="text" id="from name="from" value="">');
label.appendTo('body');
// set up datepicker
label.find('#from').datepicker();
回答by Bryan
Where are you trying to insert the label? If you want it at the beginning of the page, you can do something like this.
你想在哪里插入标签?如果你想在页面的开头,你可以做这样的事情。
var $label = $("<label>").attr('for', "from");
$label.html('Date: <input type="text" id="from" name="from" value="">');
$(function() {
$('body').prepend($label);
$(':input', $label).datepicker();
});
回答by Ilia G
1) You are missing closing quote at the end of the ID attribute.
2) You didn't append the label itself to anything.
1) 您在 ID 属性的末尾缺少右引号。
2)您没有将标签本身附加到任何东西上。