繁体   English   中英

使用jQuery设置动态创建的文本框的值

[英]Setting the value of a dynamically created text box with 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/>");

也没帮助

我的价值在哪里?

编辑:SOLTUION

所以,进一步在堆栈中我将我构建的DOM转换为字符串,因为 - 就像munch所提到的那样 - 动态值没有被添加到标记中,它没有显示出来。

谢谢您的帮助

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

你仍然可以操纵你想要的所有值,你只是不会看到萤火虫的任何变化,就像你改变类别,造型等一样。

AFAIK,没有使用jQuery也是如此。 同样的事情发生在:

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

value属性仅用于设置服务器的某些值。 javascript不需要它。

此外,它取决于您正在使用的输入类型。 例如,您将看到value属性更改为隐藏输入,但不会更改文本框。

编辑:

通过将newDiv附加到正文,文本框和值将使用您的代码显示。 这是一个测试页面 您可以看到代码和预览发生的事情。 但是,由于上述原因,警报并未显示任何“值”属性。

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

var newTextBox = $('<input />')
    .attr("type", "text")
    .attr("id", "textbox")
    .attr("name", "textbox")
    .val("my text"); // <-- You can use here...

newTextBox.val("my text"); // <-- or here
newDiv.append(newTextBox);
alert(newDiv.html());

有点破解你可以做到..

var newDiv = $('<div/>');
var newTextBox;

newTextBox = $('<input/>')
    .attr("type", "hidden")
    .attr("id", "textbox")
    .attr("name", "textbox");

newTextBox.val("text");
newDiv.append(newTextBox);
newTextBox.each(function(){this.type='text';});
alert(newDiv.html());

1st将其类型定义为hidden,因为这将允许value属性,然后使用代码将其更改为text。

$("#element")[0].setAttribute("value","newvalue");

人们也可以这样做

var chip = document.createElement("div"); chip.innerHTML="some value here" card.appendChild(chip)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM