2014-03-05 75 views
0

我想获得基于属性值的属性值attr值。我如何在JavaScript中做到这一点?JQuery获取具有相同名称的属性值

<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'); 
} 
}); 
+1

'$ (this).attr('rel');',除非我在这里丢失东西? –

+0

所以你想知道如何读取rel属性?如果是这样@ShadowWizard有你的答案 – Liam

+0

@ShadowWizard,我想获得href的值,其中rel =“streams”。 $(本).attr( '相对');只会给我rel的价值。 – Fabii

回答

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'); 
    } 
}); 
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

相关问题