我有以下代码:
HTML:
<button class="button">Click this!</button>
<div id="divInDom">Div already in DOM.</div>
JS:
$(document).ready(function() {
var myStuff = {
elements: {
divInDom: $(document).find('#divInDom'),
divAppended: $(document).find('#divAppended')
}
}
$(document.body).on('click', '.button', function(event){
event.preventDefault();
$('body').append('<div id="divAppended">Div that just got appended.</div>');
var a = myStuff.elements.divInDom.outerWidth();
var b = myStuff.elements.divAppended.outerWidth();
alert('Width of div that was already in DOM: ' + a);
alert('Width of div that just got appended: ' + b);
});
});
实时样本:http://jsfiddle.net/uq62zz9h/
a
会返回div的宽度,而b
则会赢得
在这种情况下我可能会误用jQuery,但是可以通过从对象调用属性来使b
返回附加div
的宽度吗?
答案 0 :(得分:3)
此行$(document).find('#divAppended')
返回一个空数组,因为此时该元素不存在。
jQuery已经评估了选择器并且什么都没找到,你需要在添加元素之后执行它。
您可以将divInDom
和divAppended
作为函数来实现,以便在每次调用时评估选择器。
$(document).ready(function() {
var myStuff = {
elements: {
divInDom: function() {
return $(document).find('#divInDom');
},
divAppended: function() {
return $(document).find('#divAppended');
}
}
}
$(document.body).on('click', '.button', function(event){
event.preventDefault();
$('body').append('<div id="divAppended">Div that just got appended.</div>');
var a = myStuff.elements.divInDom().outerWidth();
var b = myStuff.elements.divAppended().outerWidth();
alert('Width of div that was already in DOM: ' + a);
alert('Width of div that just got appended: ' + b);
});
});