2013-11-22 61 views
0
<div id="Blah"> 
    <h2>Blubb</h2> 
    <p>Lorem ipsum ...</p> 
</div> 

出於測試目的,我需要一個班輪JS呈現的「嗒嗒」的H2喜歡這裏內部:oneliner-javascript:呈現父標籤的屬性?

<div id="Blah"> 
    <h2>Blubb (Blah)</h2> 
    <p>Lorem ipsum ...</p> 
</div> 

我知道這會很容易與jQuery,但我絕對初學者用JS/JQuery的...

似乎同樣喜歡這裏:get href attribute of enclosing link tag

但我不知道如何調用它在我的HTML。請加minial完整的HTML文件,不僅jQuery的片段...

+0

鏈接是不同的東西。你想把文本放在'h2'的右邊?你將如何在jQuery中做到這一點? – putvande

回答

1

嘗試

jQuery(function ($) { 
    $('div.myclass > h2').text(function (_, text) { 
     return text + " (" + $(this).parent().attr('myattr') + ")"; 
    }) 
}) 

演示:Fiddle

+0

不錯,我將如何選擇基於CSS類的div? – Bastl

+0

我將如何使用任意(自定義)屬性而不是id? – Bastl

+0

@Bastl看到更新 –

0
$("h2").text($("h2").text()+" (Blah)"); 
//or if you want div "Blah" id set as append text then 

$("h2").text($("h2").text()+" ("+$(this).closest("#Blah").attr('id')+")"); 
0

嘗試

fiddle Demo

jQuery(function() { 
    $('#Blah h2').text(function (_, old) { 
     return old + '(' + $(this).parent().attr('id') + ')'; 
    }); 
}) 
+0

爲什麼倒票? –

0
var a = $('h2:contains("Blubb")').text(); 
$('h2:contains("Blubb")').text(a+' (Blah)') 
0

另一種選擇是

$h2 = $('div > h2'); 
$h2.append(' ('+$h2[0].parentNode.id+')'); 

FIDDLE