【问题标题】:Return one specific data返回一个特定的数据
【发布时间】:2016-12-03 06:15:54
【问题描述】:

我想专门从 xml 返回一个数据。

如果 nameOfBusiness = Restaurant,则返回所有评分(三个餐厅),其中 itemname 包含 Restaurant。

我怎样才能让它只提醒一个餐厅而不包括其他 2 个餐厅(带有 Steams 和 Origins)?

这是我的 xml:

<resultitem>
 <itemname>Restaurant</itemname>
 <rating>3</rating>
</resultitem>
<resultitem>
 <itemname>Restaurant Origins</itemname>
 <rating>4</rating>
</resultitem>
<resultitem>
 <itemname>Restaurant Steams</itemname>
 <rating>4.1</rating>
</resultitem>

这是我的 ajax 代码:

$.ajax({
  type: 'GET',
  url: 'someURL.xml',
  dataType: 'xml',
  success: function(xml) {
    var found = $(xml).find('resultitem itemname:contains("' + nameOfBusiness + '")');
    if (!found.length) {
      alert("Rating not published yet");
      return;
    }
    found.each(function() {
      var rating = $(this).parent().find('rating').text();
      alert("The rating for " + nameOfBusiness + " is " + rating);
    })
  }
});

【问题讨论】:

  • 而不是found.each循环只处理第一项found[0]

标签: jquery html ajax xml


【解决方案1】:

对于第一项,您可以使用:

const foundRating = found.first().parent().find('rating').text();

您也可以通过返回false 来退出循环break:

found.each(function(i, v) {
    if (i === 0) {
        var rating = $(this).parent().find('rating').text();
        alert("The rating for " + nameOfBusiness + " is " + rating);
        return false;
    }
});

jQuery each docs

【讨论】:

  • 我也想知道,我如何在 上包含我使用的元素?我有 但我忘记将它包含在 xml 中。是类似于.... find('resultitem itemname:contains("' + nameOfBusiness + '") itemaddress:contains("'+addressOfBusiness+'")')
  • 没有用于验证文本值的 CSS 选择器,但您可以执行 $('itemname').map(function(i,v) {return $(v).text()}); 之类的操作(这在浏览器中有效,但在 JSbin 中无效)。 JSbin 需要这样的另一个函数:var text = $('itemname').map(function(i,v) {return $(v).text()}); text = $.makeArray(text);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多