2017-02-08 15 views
1

我想訪問json API並檢索一些數據,例如:標題,類別和圖像。如何使用打字機獲取圖像源的值?

問題是我不能得到圖像的來源。

我曾嘗試:

  • field_image [0]的.src
  • field_image [0] .getAttribute( 'SRC')
  • field_image [0] .attr( 'SRC')
  • 等。

但沒有任何工作正常,它給我「功能未找到」或「未定義」。

請幫助..和感謝..

這個例子,我檢索一個JSON對象。

Object 
    body:"this is a normal text" 
    field_category:"myCat" 
    field_image:Array[2] 
    0: 
    "<img typeof="foaf:Image" src="http://rs.ksu.edu.sa/sites/rs.ksu.edu.sa/files/styles/750x407/public/2017-01-19-photo-00000063.jpg?itok=g4DouHqQ" width="750" height="407" alt="" />" 
    1: 
    "<img typeof="foaf:Image" src="http://rs.ksu.edu.sa/sites/rs.ksu.edu.sa/files/styles/750x407/public/20150817-img_0604.jpg?itok=zNXuoh5t" width="750" height="407" alt="" />" 

    length:2 
    __proto__: 
    Array[0] 
    field_issue:"1260" 
    field_page_number:"19" 
    field_sub_title:"sub" 
    field_sub_title1: 
    Array[0] 
    field_sub_title2: 
    Array[0] 
    nid:"1269" 
    title:"<a href="/issue-1260/1269">this is title</a>" 
    __proto__: 
+0

field_image元素似乎是原始文本字符串,而不是html元素。如果你使用jQuery,你可以使用jQuery.parseHTML()。 –

回答

3

使用jQuery:

var url = $(field_image[0]).attr('src'); 

這將解析HTML字符串給你,讓你可以輕鬆地訪問屬性。

+0

或者如果你確實想用jQuery:http://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-或親 –

+0

謝謝..它幫助我太多@安德魯修士 – ridwaili

+0

@ridwaili,標記問題,如果這提供瞭解決方案。 –

1

感謝您的@Andrew Monks。他向我提供了這個鏈接https://stackoverflow.com/questions/494143,我找到了解決方案。

,這裏是最終的解決方案:

我聲明的特性:

element: HTMLImageElement; 

然後我創建這個函數,採取HTML字符串,返回的IMG SRC:

getImgSrc(htmlString){ 
    var div = document.createElement('div'); 
    div.innerHTML = htmlString; 
    this.element = <HTMLImageElement>div.firstChild; 
    return this.element.src; 
} 

我在這裏叫它:

{{this.getImgSrc(item.field_image[0])}} 
相關問題