【问题标题】:add what contains in element along with array将元素中包含的内容与数组一起添加
【发布时间】:2012-02-28 19:52:29
【问题描述】:

我正在尝试添加每个 span 的内容以及 title 属性中的值。

<div id="group-wrap" class="group">
    <span class="lbracket" title="&f">(</span>
    <span class="grouptitle" title="&f"> Group </span>
    <span class="rbracket" title="&f">) </span>
    <span class="username" title="&f"> Username </span>
    <span class="col" title="&f">:</span>
    <span class="text" title="&f"> Helo There! </span>
</div>

这是我目前所拥有的:

var str = [];
    $('#group-wrap span').each(function(){
        str.push($(this).attr('title'));
    });
    alert(str.join(''));
});

http://jsfiddle.net/B9QeK/3/

输出是&amp;f&amp;f&amp;f&amp;f&amp;f(每个标题属性的值),但预期的输出具有该值,加上跨度中的内容。属性的值应该附加在内容之前。

&f(&fGroup&f)&fUsername: &f text

我怎样才能得到这个结果?

【问题讨论】:

    标签: javascript jquery html arrays


    【解决方案1】:

    看起来你正在寻找

    str.push( this.getAttribute('title'), this.textContent || this.text );
    

    出于性能原因,您不应该为每次迭代都重新创建一个 jQuery 对象。更好的是,根本不要使用 jQuery 来接收这些值。

    JSFiddle

    顺便说一句,你可以使用 jQuerys .map() 来做的更优雅一点:

    jQuery(function($){
        var str = $('#group-wrap span').map(function(){
            return this.getAttribute('title') + this.textContent || this.text;
        }).get();
    
        alert(str.join(''));
    });
    

    JSFiddle

    参考:.map()

    【讨论】:

      【解决方案2】:
      jQuery(function($){
          var str = [];
          $('#group-wrap span').each(function(){
              str.push($(this).attr('title') + $(this).text());
          });
          alert(str.join(''));
      });
      

      Working JSFiddle

      text:

      描述:获取匹配元素集中每个元素的组合文本内容,包括它们的后代。

      docs

      【讨论】:

        【解决方案3】:

        只需使用text方法获取每个span的文本内容:

        var str = [];
            $('#group-wrap span').each(function(){
                //Push value of title attribute and text content into array:
                str.push($(this).attr('title') + $(this).text());
            });
            alert(str.join(''));
        });
        

        【讨论】:

          【解决方案4】:

          你的线路

          str.push($(this).attr('title'));
          

          应该看起来像:

          str.push($(this).attr('title') + $(this).text());
          

          虽然,这是在进行两个相同的调用$(this),所以你可以考虑缓存:

          var $this = $(this)
          str.push($this.attr('title') + $this.text());
          

          【讨论】:

            【解决方案5】:
            var str = "";
                $('#group-wrap span').each(function(){
                    str+=$(this).attr('title')+$(this).text();
                });
                alert(str);
            });
            

            【讨论】:

              猜你喜欢
              • 2016-03-07
              • 1970-01-01
              • 2017-07-09
              • 1970-01-01
              • 1970-01-01
              • 2012-02-29
              • 1970-01-01
              • 2014-05-02
              • 1970-01-01
              相关资源
              最近更新 更多