简体   繁体   English

保留一些html元素而不替换新的相同html元素

[英]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. 我的li内有复选框,我希望dlbclick可以编辑li,但是它将删除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/ 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 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 由于您具有id为li多个元素,因此请勿使用id属性,而应使用class,因为元素的ID在文档中必须唯一

Check this : 检查一下:

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

Simply takte the checkbox outside the 'li'. 只需选中“ li”之外的复选框即可。 You can then arrange the checkbox in line with your text using CSS. 然后,您可以使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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