2011-04-06 26 views
4

我正在爲某些特別格式化的HTML編寫JQuery HTML解析器,我需要爲值查詢內聯樣式。在JQuery中查詢內聯樣式屬性

在我通過特定輸入字段加強和保存了這個特殊的風格發揮到了數組的代碼...

首先這裏是我使用的步驟,通過這些輸入字段和搶寬度的代碼。這工作,但不會返回正確的寬度值(我想EM值)。

$('.inputBox',this).each(function(index) 
{ 
    widthArray[widthArray.length] = $(this).attr('width'); 
} 

下面是輸入框

<input style="width:1.9500000000000002em;" maxlength="3" tabindex="1" class="inputBox" type="text"> 

任何幫助理解一個的簡化示例。謝謝!

回答

8

當然最簡單的方法是從的thisstyle屬性得到它。

$('.inputBox', this).each(function(index) { 
    widthArray[widthArray.length] = this.style.width; 
}); 

Live Demo

從這裏開始,這僅僅是猜測醉酒:從理論上說,你可以得到style屬性和分裂在那裏發現的基礎上;值。然後,您可以進一步將它們拆分爲:以獲取鍵值對。

是這樣的:

$('.inputBox', this).each(function(index) { 
    var stylestemp = $(this).attr('style').split(';'); 
    var styles = {}; 
    var c = ''; 
    for (var x = 0, l = stylestemp.length; x < l; x++) { 
    c = stylestemp[x].split(':'); 
    styles[$.trim(c[0])] = $.trim(c[1]); 
    } 
    widthArray[widthArray.length] = styles.width; 
}); 

Live Demo of Drunken Speculation

+0

狡猾。感謝:D – 2011-04-06 09:48:28

-4

因爲你檢查attrubute而不是風格寬度

$(this).css('width') 
+0

謝謝,但我已經試過了,它會返回一個像素寬度。我想要在樣式中聲明的實際EM值。 – 2011-04-06 09:28:02

+0

-1這不起作用。見http://stackoverflow.com/questions/5475589/jquery-css-function-not-returning-expected-values/5476075#5476075 – kapa 2011-04-06 10:19:53

1

可惜的jquery的實際上僅用PX-值 - 它是與寬度()方法,b.t.w.相同

有點髒,但如果「寬度」是你輸入的唯一風格元素,你可以檢索整個風格字符串,並以自己解析它:

var inputStyle = $("input").attr('style'); 
// make an array [ 'width', '1.9500000000000002em;' ] 
var styleParts = inputStyle.split(':'); 
// make float from 1.9500000000000002em; --> 1.95 
var widthEm = parseFloat(styleParts[1]); 

由於浮動精度在JavaScript你將在最後失去你的... 0000002。 也許你需要用字符串方法解析數字。

+0

很高興知道,謝謝! – 2011-04-06 10:32:49