【问题标题】:Extract the text in a Element then append it to an attribute with using jQuery提取元素中的文本,然后使用 jQuery 将其附加到属性
【发布时间】:2012-08-08 18:53:31
【问题描述】:

我在这个链接上捎带... Extract the Text in a Element with JQuery

我喜欢提取元素中的文本,然后将其附加到这样的属性中......

jQuery

$(document).ready(function() {
    var text;
    $(".parent span").contents().each(function(i) {
        if(this.nodeName == "#text") text = $(this).text();   
        $(".child").attr("ref", text);
    });
});

HTML

<div class="parent">
  <div class="child"> </div>
  <span><strong>bla bla bla</strong>Child-1</span> </div>
<div class="parent">
  <div class="child"> </div>
  <span><strong>bla bla bla</strong>Child-2</span> 
</div>

我不断在每个父母的参考中得到“Child-1”。

【问题讨论】:

  • $('#bla2').attr({ref:$('#bla').text()});
  • 您要提取什么文本并将其附加到哪里?这样做的原因是什么?

标签: jquery text attributes clone extraction


【解决方案1】:

试试这个:

$(document).ready(function() {
    $("div.child").each(function() {
        var text = "";
        $(this).next("span").contents().each(function(i) {
            if(this.nodeName == "#text") text += $(this).text();
        });
        $(this).parent().attr("ref", text);
    });
});

注意:我使用链接问题中接受的答案从第一个 div 获取所需的文本。

【讨论】:

  • @user952851 - 糟糕,我有+= 而不是正确的+。再试一次。
  • 它正在显示这个...
  • 但是......现在的问题是它没有为每个 set$(document).ready(function() { var text; $(".bla span").contents() 抓取元素.each(function(i) { if(this.nodeName == "#text") text = $(this).text(); $(".bla2").attr("ref", text); }) ; });
  • @user952851 - 我不确定我是否理解你,但如果我理解了,编辑后的代码应该可以工作。
  • @user952851 - 那么您是否希望第一个父 div 有一个 class 或“Child-1”,而第二个父 div 有一个 class 或“Child- 2"?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
  • 2011-04-12
  • 2016-07-07
  • 2017-03-01
  • 2016-12-06
  • 1970-01-01
相关资源
最近更新 更多