2012-02-20 189 views
1

我在產品銷售網站上獲得了以下代碼。將ID /類轉換爲字符串

<html> 
    <body> 

     <div class="descr"> 
       <div id="productName"></div> 
     </div> 

    </body> 
</html> 

#productName是唯一的每個產品(即blackTea,whiteTea,綠茶,等...)

我插入一個div id爲#productName_description#productName。我需要一個腳本來抓取descr:first-child的ID,並將"_description"添加到最後,並將其應用於我嘗試加載的內容。 Essenssially我想要做的是有一個自動化的腳本,將做到這一切沒有我不必每寫產品額外的javascript:

$('#kyoto_matcha').load('https://www.assamteacompany.ca/skin/assam_tea_company/script/product_descriptions.html #kyoto_matcha_description'); 

這是我得最遠。花了幾個小時在網上看到這個問題後,或試圖找出解決方案,我無法弄清楚。當通過console.log()輸出時,我不斷收到[object Object] _description。這是我所得到的最接近:

$('.descr:first-child').each(function(){ 
    var teaAccessory = $('.descr:first-child').attr('id'); 
    var description = '_description'; 

    $(this).load('https://www.assamteacompany.ca/skin/assam_tea_company/script/product_descriptions.html #' + teaAccessory + description); 
}); 
+0

這個問題是發佈代碼的外部問題,因爲attr('id')* *絕對*返回一個字符串,而不是一個對象。您關於「將ID /類轉換爲字符串」的問題無法回答,因爲它們*已經是*字符串。 – meagar 2012-02-20 19:30:08

+0

看到這個:http://jsfiddle.net/QfDv9/ – 2012-02-20 19:31:35

+0

好吧,所以product_descriptions.html包含所有的產品描述,你試圖提取它們並將它們插入到你的新文檔? – Dave 2012-02-20 19:32:05

回答

0

我可能會寫這樣的事情

$('.descr').each(function(){ 
    var teaAccessory = $(this).children().first().attr('id'); // just using $(this).children().attr('id'); should also work 
    var description = '_description'; 

    $(this).load('https://www.assamteacompany.ca/skin/assam_tea_company/script/product_descriptions.html #' + teaAccessory + description); 
}); 

我想我明白你正在尋找改變的ID屬性?這將是代碼。

$('.descr').each(function(){ 
    $div = $(this).children().first(); 
    $div.attr('id', $div.attr('id')+'_description'); 

    $div.load('https://www.assamteacompany.ca/skin/assam_tea_company/script/product_descriptions.html #'+$div.attr('id')); 
}); 
+0

謝謝,但是這會將#productName替換爲#productName_description而不是放置在裏面。 – 2012-02-20 19:55:57

+0

我想我明白你想要什麼。我添加了另一個碼位。 – rtconner 2012-02-21 02:34:05

0

你的代碼會通過ajax爲.descr的每一次發生加載相同的頁面 - 可能不是你想要的。另外,我從來沒有運氣與load()。試試這個:

var url = 'https://www.assamteacompany.ca/skin/assam_tea_company/script/product_descriptions.html'; 
$.get(url, function(data) { 
    var $description = $(data) // make a jQuery object from the returned data 
    $('.descr:first-child').each(function(){ 
     // construct the ID to search for 
     var teaAccessory = $(this).attr('id')+'_description'; 
     // insert the html from the target page 
     $(this).html($(teaAccessory, $description).html()) 

    }); 
}); 
+0

我相當肯定,加載每個「.descr」的描述實際上是OP的意圖.... – RozzA 2015-11-10 21:16:43