简体   繁体   中英

Insert elements into an element with JQuery

I'm trying to create a ToDo list with JQuery. I'd like to add a checkbox into each <li> element.

My code is:

$('ul').append($('<li>')
               .attr('id', '' + counter + '')
               .addClass('todo')
               .append(text))
       .append('<input type="checkbox" />');

this appends a checkbox after the li element but not in it. How do I insert the checkbox directly into the li element?

what your code did, is to add the checkbox into the ul element instead of the li element.

try:

var $li = $('<li />').attr('id', counter).addClass('todo').append('<input type="checkbox" />').append(text);
$('ul').append($li);

hope that helps.

You need to append the checkbox to the li , not ul .

  $('ul').append($('<li>')
           .attr('id', '' + counter + '')
           .addClass('todo')
           .append(text)
           .append('<input type="checkbox" />'));
$('ul').append(
    $('<li />', {id : counter, 'class' : 'todo'}).append(
        text, $('<input />', {type: 'checkbox'})
    )
)

You can make code much more readable and easier to support. For example like this:

var $li = $('<li>', {
    id: counter,
    className: 'todo',
    text: text
})
.append('<input type="checkbox" />');

$('ul').append($li);

http://jsfiddle.net/7Ter2/

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