.each(从html元素生成下拉列表,替换元素)

.each (generate dropdown from html element, replace element)

本文关键字:元素 下拉列表 替换 html each      更新时间:2023-09-26

我需要一些帮助。我在div中有一些数据。我设法从每个div中提取数据,并从中创建下拉列表。现在,某些元素(示例中的class.change)应该被那些下拉列表所取代,我陷入了每个函数的困境。如何解决?

// convert data from div to dropdown
$('.wrap').each(function () {
    var $select = $('<select />');
    $(this).find('.answer').each(function () {
        var $option = $('<option />');
        $option.attr('value', $(this).next().html()).html($(this).html());
        $select.append($option);
    });
    $(this).replaceWith($select);
    // replace .change with dropdown
    $(".change").each(function () {
        $(this).replaceWith($select);
    });
});

http://jsfiddle.net/shinzon/jgj6whmx/

问题是您试图用为每个.wrap创建的下拉列表填充每个.change,而您只想更改行中的下一个。

// convert data from div to dropdown
$('.wrap').each(function () {
    var $select = $('<select />');
    $(this).find('.answer').each(function () {
        var $option = $('<option />');
        $option.attr('value', $(this).next().html()).html($(this).html());
        $select.append($option);
    });
    // remove old unneeded div
    $(this).remove();
    // replace first .change with dropdown
    $(".change:first").replaceWith($select);
});

Fiddle:http://jsfiddle.net/jgj6whmx/5/