仅显示与jquery中的url id匹配的产品

时间:2016-03-16 21:49:15

标签: javascript jquery html xml

我正在尝试使用html表和xml填充我的product.html页面。我的数据在var" productsXmlString"下。这不能改变。我的问题是我的代码放置的所有产品不仅仅是与url具有相同ID的产品。

var productsDomTree = $.parseXML(productsXmlString);
var $products = $( productsDomTree );

var url = $(location).attr('href');
var urlid = url.substring(url.lastIndexOf('=') + 1);

$products.find('product').each(function(){
var id = $(this).find('id').text();
var title = $(this).find('title').text();
var brand = $(this).find('brand').text();
var price = $(this).find('price').text();
var desc = $(this).find('description').text();

$('#mainTable > tbody').append("
<tr>
  <td>" + id + "</td>
  <td>" + title + "</td>
  <td>" + brand + "</td>
  <td>" + price + "</td>
  <td>" + desc + "</td>
</tr>

我的数据太长,无法包括在这里,但它的一个例子是:

'<product top-level-category="Compact" sub-level-category="All-in-one"> <id>0019</id><title>NIKON COOLPIX</title><brand>Nikon</brand><price>200</price><description>example text</description>'

任何解决方案都将是大量的帮助

1 个答案:

答案 0 :(得分:0)

您可以使用filter确保每个产品符合特定条件。以下代码段重点介绍了如何执行此操作:

var id = /* read the id from the url */;

var $filtered = $products.find('product').filter((i, el) => {
  // Only return true if id matches the value in the url
  return $(el).find('id').text() === id;
});