0

以下のスニペットは問題を示しています。ユーザーが 2 番目のテキスト入力フィールドに何らかの入力を追加すると、アラートには新しい入力が含まれません。

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

4

3 に答える 3

3

関数は.html()、更新された DOM 属性を取得しません。更新された属性を手動で取得する必要があります。以下のデモを確認してください。

デモ: 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);

参照: Firefox の jQuery html() (.innerHTML を使用) は DOM の変更を無視する

于 2012-06-11T19:16:46.230 に答える
0

正しいかどうかはわかりませんが、val() 関数を使用してテキストボックスの値を取得してみてください。ドキュメントhttp://api.jquery.com/val/で詳細情報を参照してください。

于 2012-06-11T19:14:37.803 に答える
0

ユーザーがinput要素に入力を入力しても、その入力の HTML は更新されません。したがって、それを呼び出し.html()ても、フィールドにある新しいデータは得られません。

入力フィールドのすべての値を取得したい場合は、次のようにすることができます。

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

map呼び出すと最初の要素val()の値しか得られないため、使用する必要があります。input

于 2012-06-11T19:19:52.110 に答える