简体   繁体   中英

retain some html elements without replace new same html element

I have checkboxs within my li, I want the li to be editable by dlbclick, but it will remove the checbox. I can include the checkbox together with my text value, but I do not want to do so, any other way?

http://jsfiddle.net/64V4p/4/

$(document).on('dblclick', '#li', function () {
    oriVal = $(this).text();
    $(this).text("");
    input = $("<input type='text' id='input'>");
    input.appendTo($(this)).focus();

});

$(document).on('focusout', '#input', function () {
    if ($(this).val() != "") {
        newInput = $(this).val();
        $(this).hide();
        $(this).closest('li').text(newInput);
    } else {
        $(this).closest('li').text(oriVal);
    }

});

html

<ul>
    <li id="li">
        <input type="checkbox" name="1" value="1">item 1</li>
    <li id="li">
        <input type="checkbox" name="2" value="2">item 2</li>
</ul>

See

<ul>
    <li class="li">
        <input type="checkbox" name="1" value="1"/><span>item 1</span>
    </li>
    <li class="li">
        <input type="checkbox" name="2" value="2"/><span>item 2</span>
    </li>
</ul>

and

$(document).on('dblclick', '.li', function () {
    var $this = $(this),
        text = $.trim($this.text());
    $this.data('text', text);
    $("<input />", {
        value: text,
            'class': 'edit'
    }).appendTo($(this).find('span').empty()).focus();
    $this.find('input[type="checkbox"]').hide();
});

$(document).on('focusout', '.edit', function () {
    var value = $.trim(this.value),
        $li = $(this).closest('li');
    $li.find('span').text(value == '' ? $li.data('text') : value)
    $li.find('input[type="checkbox"]').show();
});

Demo: Fiddle

Since you have multiple elements with the id li do not use id attribute, use class instead because ID of an element must be unique in a document

Check this :

http://jsfiddle.net/64V4p/4/

Simply takte the checkbox outside the 'li'. You can then arrange the checkbox in line with your text using CSS.

<ul>
    <input type="checkbox" name="1" value="1"><li id="li">item 1</li>
    <input type="checkbox" name="2" value="2"><li id="li">item 2</li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM