700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > html+li标签+高度 有时在使用Jquery插入LI元素时 JavaScript不会调整UL元素的高度

html+li标签+高度 有时在使用Jquery插入LI元素时 JavaScript不会调整UL元素的高度

时间:2018-11-08 00:42:07

相关推荐

html+li标签+高度 有时在使用Jquery插入LI元素时 JavaScript不会调整UL元素的高度

要真正地回答您问的问题,如果您只想在所有图像加载完成时调用resize(),那么您需要为这些图像安装onload处理程序,并且当您记录最后一个图像的加载时,您可以调用resize()函数.你可以这样做(下面的代码说明):

var remainingAnswerImages = 0;

function categoryAnswerImageLoadHandler() {

--remainingAnswerImages;

if (remainingAnswerImages === 0) {

resize();

}

}

function populateUnsetAnswers(unsetCategoryAnswers) {

// add one extra to the image count so we won't have any chance

// at getting to zero before loading all the images

++remainingAnswerImages;

var possibleAnswers$= $('#categoryQuestionArea #possibleAnswers');

for (i in unsetCategoryAnswers) {

if (unsetCategoryAnswers.hasOwnProperty(i.toString())) {

possibleAnswers$.append(categoryAnswerLiTag(unsetCategoryAnswers[i]));

}

}

// remove the one extra

--remainingAnswerImages;

// if we hit zero on the count, then there either were no images

// or all of them loaded immediately from the cache

// if the count isn't zero here, then the

// categoryAnswerImageLoadHandler() function will detect when it does hit zero

if (remainingAnswerImages === 0) {

resize();

}

}

function categoryAnswerLiTag(unsetCategoryAnswer) {

var obj = document.createElement("li");

obj.id = unsetCategoryAnswer.id;

if (unsetCategoryAnswer.image) {

// count this image

++remainingAnswerImages;

var img = new Image();

img.onload = img.onerror = img.onabort = categoryAnswerImageLoadHandler;

img.title = unsetCategoryAnswer.text;

img.style.height = unsetCategoryAnswer.image.height;

img.src = "/trainingdividend/rest/streaming/" + unsetCategoryAnswer.image.fileName;

obj.appendChild(img);

} else {

obj.innerHTML = unsetCategoryAnswer.text;

}

return obj;

}

通过说明,此代码进行了以下更改:

>添加一个变量remainingAnswerImages来跟踪还需要加载多少图像.>为每个< img>添加一个onload处理程序标签被创建,所以我们可以跟踪加载的时间.>每次我们使用onload处理程序生成一个标签的HTML,增加remainingAnswerImages.>完成添加所有HTML后,请检查其余的AustwerImages计数以查看是否为零(只有当没有图像或者所有图像立即从浏览器缓存中加载时,才会这样).如果是这样,请立即调用resize().>在将为每个图像调用的onload处理程序中,减少remainingAnswerImages,如果计数达到零,调用resize().>在添加图像时,添加一个额外的剩余的作为一个门,以防止得到零计数,直到我们完成添加图像.完成添加图片后,再加一点.>我还重写了类别AnswerLiTag()函数,直接创建DOM对象,而不是将一串字符串并入HTML.在这种情况下,代码是更清洁的阅读和维护.>我还将$(‘#categoryQuestionArea #possibleAnswers’)从你的for循环中移出,因为它每次都解析为同样的事情.更好地在循环之前做一次.此外,在大多数情况下,这可以简化为$(‘#possibleAnswers’),因为ids应该在页面中是唯一的.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。