【问题标题】:oneliner-javascript: render parent tag's attribute?oneliner-javascript:渲染父标签的属性?
【发布时间】:2013-11-22 09:25:03
【问题描述】:
<div id="Blah">
  <h2>Blubb</h2>
  <p>Lorem ipsum ...</p>
</div>

出于测试目的,我需要一个在 h2 中呈现“Blah”的单行 js,如下所示:

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

我知道使用 jquery 会很容易,但我绝对是 JS / JQuery 的初学者...

看起来和这里一样:get href attribute of enclosing link tag

但我不知道如何在我的 html 中调用它。请添加最小的完整 html 文件,而不仅仅是 jquery sn-ps...

【问题讨论】:

  • 链接有所不同。您只想将文本放在h2 中,对吗?你会如何在 jQuery 中做到这一点?

标签: javascript jquery html


【解决方案1】:

试试

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

演示:Fiddle

【讨论】:

  • 很好,我将如何根据 css 类选择 div?
  • 如何使用任意(自定义)属性而不是 id ?
【解决方案2】:

试试

fiddle Demo

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

【讨论】:

    【解决方案3】:
    var a = $('h2:contains("Blubb")').text();
    $('h2:contains("Blubb")').text(a+' (Blah)')
    

    【讨论】:

      【解决方案4】:

      另一种选择是

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

      FIDDLE

      【讨论】:

        【解决方案5】:
        $("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')+")");
        

        【讨论】:

          猜你喜欢
          • 2019-02-25
          • 2019-11-26
          • 2020-10-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-22
          相关资源
          最近更新 更多