Jquery change css property after appending an image
im working with jquery. I appended an image into my div-element. it works great. i want to change a css property (like max-heigth or width etc.) with a js-function.
but nothing works... i tried it with an image fix on the page (withouth appending before, strict in the html..) 开发者_C百科and that works...
does anybody has an idea??
my function looks like this:
function makeBigger() {
var origHeight = $("#articlePicture").css("max-height");
var newHeight = parseInt(origHeight.replace("px", ""));
newHeight+=25;
newHeight+="px";
$("#articlePicture").css("max-height", newHeight);
}
thanks!
edit: important to say: it doesn't work only with the appendet picture, firebug etc. everything tried - works!
edit2: appending-function (kind of an easy version of it..):
function appendThis(artikelNumber, pictureToAppend) {
img="<img src='"+pictureToAppend+"' alt='articlePicture' id='articlePicture' class='articlePicture' />";
$('.article'+artikelNumber+'Text').append(img);
}
There are two things in your appendThis
function that could be the reason for it not working.
Every time you run this function (and append a new image), you assign the same ID to that image. That is not good, ID's have to be unique on the page. If you have multiple elements with the same ID, jQuery won't be able to select them. You should use the class attribute instead. That way, you can select the images like so:
$('img.articlePicture')
You didn't declare the variable
img
, thus making it an implicit global. This should be avoided, since it can lead to unexpected name-collisions.
I fixed both issues below:
function appendThis(n, url) {
var img = '<img src="' + url + '" class="articlePicture" alt="Picture">';
$('.article' + n + 'Text').append(img);
}
Also, here is an optimized version of your makeBigger function:
function makeBigger() {
$("img.articlePicture").css('max-height', function(i,v) {
return parseInt(v, 10) + 25 + 'px';
});
}
if you want it to be bigger just change the height or set the min-height. max-height will not make it bigger it just won't allow it to grow beyond that height.
精彩评论