开发者

Jquery append element and then alter css?

I'm attempting to create a div tag and then alter it via css, but for some reason its not working here's my code:

$('#draw').click(function(e){
  var divToAdd = "<div id='box' style='display:block;开发者_如何学运维background-color:red;width:100px;height:100px'></div>";
  $("#area").append(divToAdd);
});
$('#left').click(function(e){
  //var leftNow = document.getElementById("box").left + 1;
  alert(document.getElementById("box").left);
  $("#box").css('left',leftNow);
});
$('#right').click(function(e){
  var leftNow = document.getElementById("box").left - 1;
  $("#box").css("left","90");
});

So for some reason the value of document.getElementById("box").left is undefined. I've been trying to figure this out for a while, i've probably got something wrong in my syntax perhaps? Any help would be appreciated, thanks alot! Thank you Nick Craver.


You would need .style.left, or $("#box").css('left'); in this case.

But...there's an easier way, like this:

$("#box").css("left","-=1");

You can just make it relative this way, same for +=, keep it simple :)


Here I have two suggestions:

(1)Use jQuery object instead of object itself

var divToAdd = $("<div id='box' style='display:block;background-color:red;width:100px;height:100px'></div>");

Actually the expression above is not so good either, to make it more 'jQuery":

var divToAdd = $('<div></div>').css('background-color','red').css....

(2) Keep using jQuery if you involved it

$('#box').css('left') instead of document.getElemengById(...)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜