使用jQuery设置动态创建的文本框的值 [英] Setting the value of a dynamically created text box with jQuery

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

问题描述

使用以下代码

var newDiv = $(document.createElement("div"));
var newTextBox;

newTextBox = $(document.createElement("input"))
    .attr("type", "text")
    .attr("id", "textbox")
    .attr("name", "textbox");

newTextBox.val("text");
newDiv.append(newTextBox);
alert(newDiv.html());

我得到以下内容

<input name="textbox" id="textbox" type="text">

我对

$("#textbox").val("test");

使用

newTextBox = $("<input/>");

也没有帮助

我的价值在哪里?

解决方案

因此,在堆栈的更深处,我正在将构建的DOM转换为字符串,并且由于-如提到的munch-动态值未添加到标签中,因此未显示.

So, further up in the stack I was converting the DOM I built to a string and since - like munch mentioned - the dynamic value doesn't get added to the tag, it wasn't showing up.

感谢您的帮助

推荐答案

jQuery不会将值放入创建的元​​素的生成的html中. .attr('value', 'blah').val()都获取在文本输入中输入或更改的内容的当前值,并允许您在查看页面上的输入或将其提交到服务器时看到该值.但是,在查看html时看不到它.

jQuery will not put the value into the created element's generated html. Both .attr('value', 'blah') and .val() get the current value of what's been entered or changed in the text input, and allow you to see that value when you look at the input on the page or submit it to the server. However, you will not see it when looking at the html.

您仍然可以随意操作所需的值,就像在类更改,样式等操作中一样,萤火虫中看不到任何更改.

You can still manipulate the value all you want, you just won't see any changes in firebug, like you do with class changes, styling, etc.

AFAIK,这与不使用jQuery的情况相同.同样的事情发生在:

AFAIK, this is the same without using jQuery. The same thing happens with:

document.getElementById('textbox').value = 'my text'; 

value属性仅用于从服务器设置某些值.使用javascript不需要.

The value attribute is only to set something's value from the server. It's not needed with javascript.

此外,这取决于您使用的输入类型.例如,您将看到值属性在隐藏的输入下发生了变化,但在文本框上没有发生.

Also, it depends on the type of input that you're using. For example, you will see the value attribute changes with a hidden input, but not with the textbox.

通过将newDiv附加到主体,使用您的代码显示文本框和值. 这是一个测试页.您可以同时看到代码和发生的事情的预览.但是,由于上述原因,该警报未显示任何值"属性.

By appending newDiv to the body, the text box and the value show up using your code. Here's a test page. You can see both the code and the preview of what happens. The alert though, does not show any 'value' attribute for reasons explained above.

这篇关于使用jQuery设置动态创建的文本框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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