克隆不克隆选择值

我没想到,但是以下测试在克隆值检查上失败了:


test("clone should retain values of select", function() {

    var select = $("<select>").append($("<option>")

                              .val("1"))

                              .append($("<option>")

                              .val("2"));

    $(select).val("2");

    equals($(select).find("option:selected").val(), "2", "expect 2");

    var clone = $(select).clone();

    equals($(clone).find("option:selected").val(), "2", "expect 2");

});

这是正确的吗?


牧羊人nacy
浏览 514回答 3
3回答

FFIVE

用Chief7的答案制作了一个插件:(function($,undefined) {&nbsp; &nbsp; $.fn.cloneSelects = function(withDataAndEvents, deepWithDataAndEvents) {&nbsp; &nbsp; &nbsp; &nbsp; var $clone = this.clone(withDataAndEvents, deepWithDataAndEvents);&nbsp; &nbsp; &nbsp; &nbsp; var $origSelects = $('select', this);&nbsp; &nbsp; &nbsp; &nbsp; var $clonedSelects = $('select', $clone);&nbsp; &nbsp; &nbsp; &nbsp; $origSelects.each(function(i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $clonedSelects.eq(i).val($(this).val());&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; return $clone;&nbsp; &nbsp; }})(jQuery);仅对其进行了简短测试,但似乎可以正常工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JQuery