JQuery获取具有相同名称的属性值

时间:2014-03-05 15:51:07

标签: javascript jquery xml

我希望根据 rel attr的值获得 href attr值。我如何在javascript中执行此操作?

<links>
    <link href="https://someurl/index/16380" rel="self"/>
    <link href="https://someurl/index/16380/streams?lang=en" rel="streams"/>
    <link href="https://someurl/index/16380/bif" rel="bif" />
</links>
沿着这条路走来......

$(xml).find('link').each(function(){
 if(rel == 'streams'){
   this.streamurl = $(this).attr('href');
 }
});

2 个答案:

答案 0 :(得分:4)

$(xml).find("link[rel=streams]")
      .each(function(i,lnk) {
          lnk.streamurl = lnk.href; 
      })

或者

$(xml).find("link[rel=streams]")
      .prop("streamurl", function() {
          return this.href; 
      })

您的原始代码几乎是正确的。只需要这个:

if(this.rel == 'streams'){

而不是:

if(rel == 'streams'){

打开您的开发者控制台,您可能会看到类似的内容:

  

ReferenceError: rel is not defined

答案 1 :(得分:1)

$(xml).find('link').each(function(){

  //prevents your re-wrapping this multiple times
  var $this = $(this);

  //read the attribute
  if($this.attr('rel') == 'streams'){
     this.streamurl = $this.attr('href');
  }
});
相关问题