本文介绍了输入的动态修改值不反映在DOM中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取DOM以反映修改的输入值?
How can I get the DOM to reflect the modified input value?
<div>
<input value='0'>
</div>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script>
<script>
setInterval(function() {
$('input').val(parseInt($('input').val()) + 1)
console.log('div.html(): ', $('div').html())
}, 1000)
</script>
推荐答案
以下内容似乎适用于我:
The following seems to work for me:
所有这一切都归功于gnarf这里和他的formhtml:
All credit to gnarf here and his formhtml:
所以修改后的代码将是:
So your modified code would be:
<div>
<input value='0'>
</div>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script>
<script>
(function($) {
var oldHTML = $.fn.html;
$.fn.formhtml = function() {
if (arguments.length) return oldHTML.apply(this,arguments);
$("input,button", this).each(function() {
this.setAttribute('value',this.value);
});
$("textarea", this).each(function() {
// updated - thanks Raja!
this.innerHTML = this.value;
});
$("input:radio,input:checkbox", this).each(function() {
// im not really even sure you need to do this for "checked"
// but what the heck, better safe than sorry
if (this.checked) this.setAttribute('checked', 'checked');
else this.removeAttribute('checked');
});
$("option", this).each(function() {
// also not sure, but, better safe...
if (this.selected) this.setAttribute('selected', 'selected');
else this.removeAttribute('selected');
});
return oldHTML.apply(this);
};
//optional to override real .html() if you want
// $.fn.html = $.fn.formhtml;
})(jQuery);
setInterval(function() {
$('input').val(parseInt($('input').val()) + 1)
console.log('div.html(): ', $('div').formhtml())
}, 1000)
</script>
这篇关于输入的动态修改值不反映在DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!