如何在函数中列出项目?

时间:2017-07-29 20:24:18

标签: javascript jquery

给出<a>这样的列表:

<tr>
    <th style="padding-right:1em">Location</th>
    <td>
        <span class="location">Lower reaches of the <a href="/wiki/Geum_River" title="Geum River">Geum River</a>, <a href="/wiki/Korea" title="Korea">Korea</a></span>
    </td>
</tr>

JS

function countryList(string) {
  let pattern = new RegExp('^.+\/wiki\/'); // adjust `RegExp`
  countryListLinks = string.replace(pattern, '');
}

我试过了,但我一无所获:

  countryLinks.each(function(){
    console.log(countryList);
  });

我试过这个,但我只得到一个项目而另一个undefined

countryLinks.forEach(countryList);

我正在尝试输出每个href但不单独/wiki/,以便我可以使用它们:

Geum_River Korea

3 个答案:

答案 0 :(得分:2)

使用map功能

function countryList(string) {
  let pattern = new RegExp('^.+\/wiki\/'); // adjust `RegExp`
  return string.replace(pattern, '');
}

var result = Array.prototype.slice.call(document.getElementsByTagName('a')).map(function(a){return a.href}).map(countryList);

console.log(result)
<tr>
    <th style="padding-right:1em">Location</th>
    <td>
        <span class="location">Lower reaches of the <a href="/wiki/Geum_River" title="Geum River">Geum River</a>, <a href="/wiki/Korea" title="Korea">Korea</a></span>
    </td>
</tr>

答案 1 :(得分:0)

按照这个简单的代码,然后使用replace方法解析

$('.location').find('a').each(function() {
    console.log($(this).attr('href'));
});

答案 2 :(得分:0)

试试这个:

<div class="ThreeWayCol OddsCol1">
   <div class="OddVal ng-pristine ng-untouched ng-valid ng-binding ng-scope ng-not-empty" ng-repeat="sel in event._matchMarket.selections" ng-model="sel" ng-class="{'Sel': oddSelections[event.id].sels[sel.id]}" ng-click="selectOdd(event,event._matchMarket,sel)">3.37</div>
   <div class="OddVal ng-pristine ng-untouched ng-valid ng-binding ng-scope ng-not-empty" ng-repeat="sel in event._matchMarket.selections" ng-model="sel" ng-class="{'Sel': oddSelections[event.id].sels[sel.id]}" ng-click="selectOdd(event,event._matchMarket,sel)">3.21</div>
   <div class="OddVal ng-pristine ng-untouched ng-valid ng-binding ng-scope ng-not-empty" ng-repeat="sel in event._matchMarket.selections" ng-model="sel" ng-class="{'Sel': oddSelections[event.id].sels[sel.id]}" ng-click="selectOdd(event,event._matchMarket,sel)">2.07</div>
</div>
let word = '/wiki/';
$('[href]').map(function(i, e) {
  var href = $(e).attr('href');
  console.log(href.substring(href.indexOf(word) + word.length, href.length));
});