2014-04-02 70 views
0

我想发送一个元素到一个函数来计算一些数据。我使用$.find()来获取元素,并使用$.width来获得它的宽度,但由于某种原因,它总是显示0.我不知道为什么。我错过了什么?

这里是一个ajax成功回调通了:

success: function(data) 
{ 
    var result = jQuery(data).find('.dir_content'); // get element with find here 
    var margin_amount = getScreenMiddle(result); // pass element to function 

    result.attr('id', full_path); 
    result.css('margin-right', margin_amount); 

    if(prev_element != null) 
    { 
     prev_element.css("margin-right", 0); 
    } 
    prev_element = result; 

    jQuery('.list-inline').append(result); 
}, 

,这里是功能

function getScreenMiddle(elem) 
{ 
    var center_pos = ($(window).width() - elem.width())/2 + "px"; 
             // this is always 0 
    return center_pos; 
} 

所以这个功能只是返回这是错误的值相同。我需要以另一种方式传递吗?

+0

你有没有尝试用另一种包装$()?例如。 ($(window).width() - $(elem).width())/ 2 +“px”; – ysrb

+0

除非将元素渲染到DOM,否则不会计算尺寸 –

+0

您需要先在文档中追加元素,然后尝试 –

回答

0

首先包括DOM文档中的结果元素,然后尝试宽度

success: function(data) 
    { 
     var result = jQuery(data).find('.dir_content'); // get element with find here 
    jQuery('.list-inline').append(result);  
    var margin_amount = getScreenMiddle(result); // pass element to function 

     result.attr('id', full_path); 
     result.css('margin-right', margin_amount); 

     if(prev_element != null) 
     { 
      prev_element.css("margin-right", 0); 
     } 
     prev_element = result; 


    },