Use a select for content editable element?

2019-08-03 19:58发布

问题:

Is it possible to bring in a select menu with a contenteditable attribute?

The following:

<p contenteditable="true" name="letter">a</p>

would become a select option once contenteditable is enabled:

<select name="letter">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

回答1:

First you need to be able to select an element based on whether or not it has the contenteditable attribute:

$('[contenteditable="true"]')

For example,

HTML:

<div>
    <p contenteditable='true'>ajdsflkjasdlfkjasdlfjdklasfD</p>
</div>
<div>
    <p contenteditable='true'>oqewrujfzkljvladswjoaiewnlei</p>
</div>
<div>
    <p contenteditable='true'>2345rtsdghwregg342534tres34</p>
</div>
<div>
    <p contenteditable='true'>a234trey36y34ttgfttqerertuityt</p>
</div>
<div>
    <p contenteditable='true'>1234rgdfs563ju6tref43f5eyrew65htew</p>
</div>


JavaScript:

$(function() {
    $('[contenteditable="true"]').each(function() {
        var parent = $(this).parent(),
            text   = $(this).text(),
            select = function() {
                var returnstring = '';
                for (var i in text) {
                    returnstring += "<option value='" + text[i] + "'>" + text[i] + "</option>";
                }
                return "<select>" + returnstring + "</select>";
            }();
        $(this).empty();
        parent.append(select);
    });
});


Here is a link to the fiddle so you can see what I'm talking about.