replace select option:selected with div



我试图将特定<div>内的所有<select>元素捕获选定的选项,然后将选择框替换为包含所选选项的<div>。这是我到目前为止的代码,但它不工作。它将页面上所有选择框中的所有选择选项复制到每个div中,而不仅仅是在它要替换的选择标签中选择的选项。

$('#receivecontainer select').each(function() {  
    $('select option:selected').replaceWith(function() {
        return $('<div>' + $('option:selected').text() + '</div>');
    });
}); 

它完全按照你的要求去做。您最后的$('option:selected')只是选择页面上所有已选择的选项。此外,不需要遍历所有选择,因为您可以简单地选择选项并遍历它们。最后,不需要将选中的选项转换为文本,只需将其添加到html字符串中,然后将其转换回元素。下面是我如何解决你的问题:

//select all selected options and iterate through them
//there is no need to select the selects because there should be no options outside a select
$('#receivecontainer option:selected').each(function() {
    var newDiv = $('<div></div>').html($(this).text()); //create an empty div and fill it with the contents of the option
    $(this).replaceWith(newDiv); //replace the option with the created div
});

只是出于好奇,把一个div在选择工作ok和一致的跨浏览器?

$("select").change(function(){
    var text = $("select option:selected")
        .not(":contains('Select one')")
        .text();
    $("<div>")
        .html( text )
        .appendTo("#container");
});

的例子。

select被改变(一个新选项被选择)时,我们将触发此功能。

函数将选中选项的文本作为新的div附加到容器中。

如果选中Select one选项,则忽略该选项。

我想出的解决方案是抓住选中的选项并将其添加到该选择元素之后的div中。然后返回并删除元素,然后再进行下一个选择。

$('#receivecontainer select').each(function() { 
            var selectvalue = $("option:selected", this).text();
            $('<div class="answer">' +selectvalue+ '</div>').insertAfter(this);
            $(this).remove();
 });

最新更新