我在动态设置元素宽度时遇到问题。我有多个.each循环,然后我追加一个应该有计算宽度的元素。这是我的代码
$.each(roomsArray, function(index, row) {
$.each(datesArray, function (dateIndex, date) {
$.each(row.calendarList, function(calendarIndex, cal) {
if(cal.roomId == row.id && new Date(cal.dateFrom).toDateString() == new Date(date).toDateString()) {
var cellElements = $(".day[data-date='" + new Date(date).toDateString() + "']");
$.each(cellElements, function (indexElement, element) {
if (element.parentElement.attributes[1].value == cal.roomId) {
var to = new Date(cal.dateTo);
var from = new Date(cal.dateFrom);
//the width should be 44*numOfDays
var numOfDays = Math.ceil((to.getTime() - from.getTime()) / (1000 * 3600 * 24));
console.log(element);
$(element).append(`
//This element needs to take the width
<div id="` + element.attributes[0].value + element.attributes[1].value + `" class="draggable"></div>
`);
//This is just something I tried to do, but it doesnt work.
$('#' + element.attributes[0].value + element.attributes[1].value).css('width', 44 * numOfDays + 'px');
}
});
}
});
})
});
提前感谢您的帮助!
答案 0 :(得分:0)
试试这个小提琴:http://jsfiddle.net/TrrCh/
我认为您在加载HTML之前尝试运行Javascript。将它绑定到document.ready并且它应该正常工作
window.onload=function(){
var elem = document.getElementById('chart');
elem.style.width = 70 + "%";
}