2012-02-20 183 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