2016-06-09 36 views
0

當試圖使用jquery計算文本寬度時,無線電輸入的「checked」屬性會丟失。 我使用下面的代碼:在不丟失DOM屬性的情況下計算文本寬度

$.fn.textWidth = function(){ 
    var html_org = $(this).html(); 
    var html_calc = '<span>' + html_org + '</span>'; 
    $(this).html(html_calc); 
    var width = $(this).find('span:first').width(); 
    $(this).html(html_org); 
    return width; 
}; 

我打電話,如下所示:

$(".checkbox-inline-tooltip").each(function() { 
    $(this).css({ 
     "position": "relative", 
     "float": "left", 
     "top": "-32px", 
     "left": $(this).prev('label').textWidth() + 30 + "px" 
    }); 
}) 

的「下一頁」標籤具有無線輸入。調用textWidth()後,屬性「checked」會丟失,導致取消選中無線電。

+0

你的html在哪裏? –

+0

請提供片段示例 – Justinas

回答

0

嘗試元素wrapInner()unwrap()。獲取innerHTML不會獲得在輸入​​元素中動態設置的屬性,如checked, disabled

$.fn.textWidth = function(){ 
    $(this).wrapInner('<span>'); 
    var width = $(this).find('span:first').width(); 
    $(this).find('span:first').contents().unwrap(); 
    return width; 
}; 
+1

它工作。謝謝 :) –

相關問題