.append我正在尝试获取动态附加元素的position()。top。
首先,我有一个创建元素的功能
var createElement = function (elementType, id, name, className, innerText) {
var el = document.createElement(elementType);
if (id) {el.id = id;}
if (name) {el.name = name;}
if (className) {el.className = className;}
if (innerText) el.appendChild(document.createTextNode(innerText));}
return el;
}
添加元素。...
$('#parent').append(createElement ( "div", "child"));
这似乎很好。但是,我需要确定孩子的最高职位来管理内容。
alert($('#child').position().top);
总是返回0; (不是我想要的值)
$('#child').click(function() {alert($(this).position().top);});
返回非零值。 (这是我想要的值)。
问题是;如何在添加动态加载的元素后立即确定其顶部位置?
答案 0 :(得分:-1)
我尚未测试,但是我认为您需要“等待”直到真正创建元素。因此,尝试像这样添加短暂的延迟。
setTimeout(function(){
alert($('#child').position().top);
}, 10);
也许像0或1这样的较短延迟而不是10也可以工作。