2014-01-14 51 views
6

你好,我有一個[對象HTMLDivElement]其中包含我想要使用的數據。對象HTMLDivElement,獲取值?

我正在使用這個。例如this.innerHTML

我的事業部結構看起來如下:

<div class="hour"> <!-- <-- my Object referes to this div --> 
    <div class="time">2000</div> 
    <img class="weather-img" src="image/rain.png"> 
    <div class="temp">-10</div> 
</div> 

我想提取時間溫度值,ERGO 和-10

我一直在閱讀http://krook.org/jsdom/HTMLDivElement.html文檔,但似乎無法找到一個圓滑的解決方案,這一點,我最好的選擇到目前爲止一直的innerHTML但感覺應該有一個更簡單的方法。任何人?

答案:var time = $(this).find('。time')。text();

回答

6

夠簡單使用jQuery:

var time = $('.time', this).text(), 
    temp = $('.temp', this).text(); 

再長一點的方式,在該工程,以及和顯示位的jQuery鏈方法的註釋中提到:

var time = $(this).find('.time').text(), 
    temp = $(this).find('.temp').text(); 

國防部編輯我的代碼可能不正確,因爲如果頁面上存在多個timetemp類別的元素,則可能會收回錯誤的數據。編輯之前我的例子顯示範圍查詢如何更好您可以:

var time = $('.hour .time').text(), 
    temp = $('.hour .temp').text(); 

jQuery.text:http://api.jquery.com/text/

+0

啊,我不清楚,我使用的 「本」。示例: var time = $(this)。$('.time')。text();但是,這似乎失敗了! –

+0

@KarlMorrison http://learn.jquery.com/about-jquery/how-jquery-works/ – iambriansreed

+1

@KarlMorrison你的示例中幾乎有正確的語法,但它需要更改爲:var time = $ (this).find('。time')。text();' –

1

此代碼將讓你的時間和溫度值使用yourDiv作爲上下文字符串:

var $div, 
    time, 
    temp; 
$div = $(yourDiv); //save the div as a jQuery collection 
        //(assuming `yourDiv` is the actual DOM node) 
time = $div 
    .find('.time') //from the div find the .time descendants 
    .text();  //get the text from the first .time descendant 
temp = $div 
    .find('.temp') //from the div find the .temp descendants 
    .text();  //get the text from the first .temp descendant 

寫這篇的更簡潔的方法是:

var time, 
    temp; 
time = $('.time', yourDiv).text(); 
temp = $('.temp', yourDiv).text(); 

在這兩個示例中,我都明確選擇了.time()而不是.html(),以防值中有任何HTML實體,在您的情況下它不會產生顯着差異,但您好像對此感興趣解析的值而不是原始的HTML。

如果您需要的值作爲數字,你會希望將字符串值轉換爲數值:

time = Number(time); 

這個快捷方式是一元+操作:

time = +time; 

所以最終的代碼如下所示:

var time, 
    temp; 
time = +$('.time', yourDiv).text(); 
temp = +$('.temp', yourDiv).text(); 

在使用之前timetemp值,一定要檢查NaN

7

如果你不想使用jQuery,你有本地getElementsByClassName()

var time = yourDOMobject.getElementsByClassName("time")[0].innerHTML; 

哪裏yourDOMobject引用您[Object HTMLDivElement]

例子:http://jsfiddle.net/PhMs4/

+0

我得到的錯誤:未捕獲TypeError:對象[對象全局]沒有方法'getElementsByClassName' –

+0

當我提醒「這個」我得到:[對象HTMLDivElement] –

+2

@KarlMorrison,不要使用'alert',使用'console.log'或'console.dir'。您將在開發控制檯中獲得更好的調試信息。 – zzzzBov