开发者

JavaScript variable value in element.append

$('#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.


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.


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>")


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)
    );


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');


If I had to guess, I'd say that your data.msg has a value that isn't allowed as an ID for selector purposes (generally starting with [-a-zA-Z] and containing [_-\da-zA-Z]. If your image name (data.msg) begins with, or is a number, I'd suggest adding a prefix to the id.

In either case, you can do this in a single statement...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜