javascript 带有输入值的内部 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12126497/
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
Inner HTML with input values
提问by Matthew Ruddy
have a brief question regarding innerHTML and input values that have been entered. See the brief example below (using jQuery for convenience):
有一个关于已输入的innerHTML 和输入值的简短问题。请参阅下面的简短示例(为方便起见,使用 jQuery):
jQuery:
jQuery:
jQuery(document).ready(function($) {
$('.send').click(function() {
alert( $('.content').html() );
return false;
});
});?
html:
html:
<div class="content">
<input type="text" name="input" value="Old Value" />
<input type="button" class="send" value="Send" />
</div>?
If you edit the input value, then click the 'Send' button, the alert shows that the innerHTML gotten contains the input with the "Old Value", rather than the value the user has entered. Why is this? And how can we get the HTML as a string with user entered input values?
如果您编辑输入值,然后单击“发送”按钮,警报会显示获得的 innerHTML 包含具有“旧值”的输入,而不是用户输入的值。为什么是这样?我们如何将 HTML 作为带有用户输入值的字符串获取?
回答by Musa
The new value is stored as a property not an attribute, the value can be obtained by inputelement.value
, modifying the value does not affect the attribute. If you want the html with the new value just set the attribute to the new value.
新值存储为属性而不是属性,值可以通过 获取inputelement.value
,修改值不影响属性。如果您想要具有新值的 html,只需将属性设置为新值。
For check boxes and radio buttons set the checked attribute, set the innerHTML for text areas, for selects set the selected attribute on the option
对于复选框和单选按钮设置checked 属性,为文本区域设置innerHTML,对于选择设置选项上的selected 属性
回答by DanCZ
this solution is better. works for more inputs.
这个解决方案更好。适用于更多输入。
$('input[type=text]').attr('value', function (i, val) { return val; });
$('input[type=checkbox],input[type=radio]').attr('checked', function () { return this.checked; });
$('textarea').html(function () { return this.value; });
$('select').find(':selected').attr('selected', 'selected');
回答by jAndy
You can't get it with .innerHTML
(.html()
). Writing into an element doesn't modify the html markup, nor will it change the value
attribute in actual markup.
你不能用.innerHTML
( .html()
)得到它。写入一个元素不会修改 html 标记,也不会更改value
实际标记中的属性。
You can only access the current content by directly asking the element for its .value
- value. Using jQuery, you can do that via .val()
too.
您只能通过直接询问来访问当前内容 元素为其.value
- 值。使用 jQuery,您也可以通过.val()
。
回答by orhanhenrik
$('#input_id').attr('value',$('#input_id').val());
will put the value into the html
$('#input_id').attr('value',$('#input_id').val());
将值放入 html