快速使用jQuery创建标签 [英] Create a label using jQuery on the fly

查看:84
本文介绍了快速使用jQuery创建标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要即时创建标签和文本字段,还需要为文本字段添加日期选择器.我需要这样的东西:

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" />

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

I have tried something like this in 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.

编辑

更准确地说,我在portlet中使用了它,而jsp页面中没有body标签.因此,当我调用附加到主体的函数时,不会.

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.

推荐答案

类似的方法会起作用:

//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演示

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

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:

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

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

这篇关于快速使用jQuery创建标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆