views:

345

answers:

5
$('#test-list').append($(document.createElement("li")).attr({id: data.msg}));
$('#'+data.msg).append($(document.createElement("img")).attr({src: "kep.php?kep=upload/"+data.msg+"&w=180;&h=150;"}));

Does not work, because of the $('#'+data.msg). param. I don't know how to fix it. I want to make a sub-element to the #test-list and name it to the value of data.msg variable.

+1  A: 

You can append the image as you create the <li>.

For example:

$('#test-list').append(
    $('<li><img src="kep.php?kep=upload/' + data.msg + '&w=180;&h=150" /></li>')
        .attr('id', data.msg)
    );
SLaks
+1  A: 

Try this out

var img = $("<img>").attr({src: "kep.php?kep=upload/"+data.msg+"&w=180;&h=150;"});
$("<li>").attr({id: data.msg}).append(img).appendTo('#test-list');

If you are using jQuery 1.4.x you can do:

var img = $("<img>",{src: "kep.php?kep=upload/"+data.msg+"&w=180;&h=150;"});
$("<li>",{id: data.msg}).append(img).appendTo('#test-list');
PetersenDidIt
+1  A: 

You are to be mixing DOM calls and jQuery in an odd way. I'd suggest doing it all with jQuery. The chain of elements is somewhat mixed up in terms of what you are appending to, and what you are specifying attributes for. You can specify the id, etc. directly in the creation of an element.

This should work:

$('#test-list').append($("<li id='"+data.msg+"'><img src='kep.php?kep=upload/"+data.msg+"&w=180;&h=150'></li>")
Alex JL
A: 

You could chain this entire task:

  $("<li>")
    .appendTo("#test-list")
    .attr("id", data.msg)
    .append("<img>")
      .find("img:first")
      .attr("src", "kep.php?kep=upload/" + data.msg + "&w=180;&h=150;");

Which produces the following:

<li id="foo">
  <img src="kep.php?kep=upload/foo&amp;w=180;&amp;h=150;">
</li>

Where "foo" was the value of data.msg.

Jonathan Sampson
A: 
Tracker1