使用jQuery从dom中选择时包含新的输入值 [英] include new input values when selecting from the dom using jquery

查看:152
本文介绍了使用jQuery从dom中选择时包含新的输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码段说明了该问题,当用户向第二个文本输入字段中添加一些输入时,警报不包括新输入.

The below snippet illustrates the problem, when the user adds some input to the second text input field, the alert does not include the new input.

<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/

推荐答案

.html()函数将无法获取更新的DOM属性.您必须手动获取更新的属性.请查看下面的演示

The .html() function will not get the updated DOM attributes. You have to manually get the updated attributes.. check below 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 ()在Firefox中(使用.innerHTML)忽略DOM更改

这篇关于使用jQuery从dom中选择时包含新的输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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