使用jquery从dom中选择时包含新的输入值

时间:2012-06-11 19:09:50

标签: jquery html dom

以下代码段说明了问题,当用户向第二个文本输入字段添加一些输入时,警报不包含新输入。

<script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    $('#click').live('click',function(){ alert($('#test').html())})
  })
</script>

<div id="test">
<input type="text" value="test"/>
<input type="text" value=""/>
</div>

<a id="click">clickme</a>

为方便起见:http://jsfiddle.net/CqPkP/

3 个答案:

答案 0 :(得分:3)

.html()函数不会获取更新的DOM属性。您必须手动获取更新的属性..请查看下面的演示,

DEMO: http://jsfiddle.net/skram/CqPkP/2/

完整代码:

$(document).ready(function() {
    $('#click').live('click', function() {
        alert($('#test').formhtml())
    })
});

(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);

参考: jQuery html() in Firefox (uses .innerHTML) ignores DOM changes

答案 1 :(得分:0)

我不确定我是否理解你的正确但是尝试使用val()函数来检索文本框的值。 请参阅文档http://api.jquery.com/val/

中的mor infos

答案 2 :(得分:0)

当用户将输入输入input元素时,它不会更新该输入的HTML。因此,在其上调用.html()将不会为您提供该字段中的新数据。

如果您想获取输入字段中的所有值,可以执行以下操作:

$('#click').live('click',function(){
  alert($('#test input').map(function() { return this.value; }).get());
});

您必须使用map,因为调用val()只会为您提供第一个input元素的值。