2014-07-18 58 views
0

我有下載從其他網頁的HTML源代碼:如何訪問jQuery中使用.find()挑選的選擇器的內部html?

$.get 
(
    'http://example.com/ex.php?something=0', 
    function(response){someFunction(response)} 
); 

再有就是它觸發功能:

function someFunction(data) 
{ 
    var someArray = []; 
    $(data).find('.someClass').each(function(loop, item) 
    { 
     someArray.push(item); 
    }); 

    $('tr:eq(1) > td:eq(0)').html(someArray[0]); //yes, I do need all the containers of class none as I'm planning to put each of them in a table cell later 
} 

到目前爲止,它工作正常,但是卻讓<container class="someClass">some text</container>到TD我只是想從中提取一些文字放在那裏。

我試圖去與

$('tr:eq(1) > td:eq(0)').html(someArray[0].html()); 

$('tr:eq(1) > td:eq(0)').html(someArray[0].contents()); 

但無論是作品。我嘗試過谷歌它,但.contents()是我發現的唯一的東西,.html()是我能想到的唯一的東西(通常當我有一個選擇器像這樣選擇$('selector')方法html()工作)。

回答

2

目前你實際上是用元素替換單元格的內容。如果你只是想它的內容,只得到它的內容:

function someFunction(data) 
{ 
    var someArray = []; 
    $(data).find('.someClass').each(function(loop, item) 
    { 
     someArray.push($(item).contents()); 
    }); 

    $('tr:eq(1) > td:eq(0)').html(someArray[0]); //yes, I do need all the containers of class none as I'm planning to put each of them in a table cell later 
} 

item.innerHTML可能工作以及(而非$(item).contents())。


FWIW,map可以在這裏有用:

function someFunction(data) 
{ 
    var someArray = $(data).find('.someClass').map(function(loop, item) 
    { 
     return $(item).contents(); 
    }); 

    $('tr:eq(1) > td:eq(0)').html(someArray[0]); //yes, I do need all the containers of class none as I'm planning to put each of them in a table cell later 
} 

這使得someArray一個jQuery對象,但你仍然可以通過[0]和這樣的訪問其內容。如果你想要一個實際的數組,添加.get()到最後:

function someFunction(data) 
{ 
    var someArray = $(data).find('.someClass').map(function(loop, item) 
    { 
     return $(item).contents(); 
    }).get(); // <=== Here 

    $('tr:eq(1) > td:eq(0)').html(someArray[0]); //yes, I do need all the containers of class none as I'm planning to put each of them in a table cell later 
} 
+0

我現在明白了;)。我只是不得不像這樣插入$(item)而不是item。非常感謝:D。 – Fiodor

1

你推整個元素到數組

someArray.push(item) 

嘗試更換與這樣的:

someArray.push($(this).text()); 

或許也許

someArray.push($(this).html()); 

修改您的代碼以演示您的推送中的關鍵問題:http://jsfiddle.net/93Cj6/

+1

我覺得我的答案更「直接」,但我也認爲T.J.克勞德的答案在下面是一個更好的答案,尤其是在地圖上()! – Spanka

+0

你很對 - 從「jq對象」改變引用。 – Spanka

相關問題