在jQuery中使用相同的类循环遍历div

时间:2015-08-03 18:44:07

标签: javascript jquery html css

您好我有很多名为itemdata的课程,我想在每个div中做一些jquery。在每个div中,有一个链接,我想复制href属性值并将其包装到相应div中的另一个<span>

我的代码如下所示。

&#13;
&#13;
<div class="itemdata" >
<a  href="www.link1" class="frame">
<img  src='...' />
</a>
<span class="wlt_shortcode_TITLE">Title 1</span>
</div>

<div class="itemdata" >
<a  href="www.link2" class="frame">
<img  src='...' />
</a>
<span class="wlt_shortcode_TITLE">Title 2</span>
</div>

<div class="itemdata" >
<a  href="www.link3" class="frame">
<img  src='...' />
</a>
<span class="wlt_shortcode_TITLE">Title 3</span>
</div>
&#13;
&#13;
&#13;

和jQuery:

&#13;
&#13;
</script>
jQuery( ".itemdata" ).each(function() {
var lk = jQuery( this ).add(".frame").attr("href");
jQuery(this).add(".wlt_shortcode_TITLE" ).wrap("<a href='" + lk + "'></a>");
});
</script>
&#13;
&#13;
&#13;

输出HTML应如下所示:

&#13;
&#13;
    <div class="itemdata" >
    <a  href="www.link1" class="frame">
    <img  src='...' />
    </a>
    <a  href="www.link1"><span class="wlt_shortcode_TITLE">Title 1</span></a>
    </div>

    <div class="itemdata" >
    <a  href="www.link2" class="frame">
    <img  src='...' />
    </a>
    <a  href="www.link2"><span class="wlt_shortcode_TITLE">Title 2</span></a>
    </div>

    <div class="itemdata" >
    <a  href="www.link3" class="frame">
    <img  src='...' />
    </a>
    <a  href="www.link3"><span class="wlt_shortcode_TITLE">Title 3</span></a>
    </div>
&#13;
&#13;
&#13;

但看起来像是:

&#13;
&#13;
        <div class="itemdata" >
        <a  href="www.link1" class="frame">
        <img  src='...' />
        </a>
        <a  href="undefined">
         <a  href="www.link1">
          <a  href="www.link1"><span class="wlt_shortcode_TITLE">Title 1</span>
          </a>
         </a>
        </a>
        </div>

        <div class="itemdata" >
        <a  href="www.link2" class="frame">
        <img  src='...' />
        </a>
        <a  href="undefined">
         <a  href="www.link1">
          <a  href="www.link1"><span class="wlt_shortcode_TITLE">Title 2</span>
          </a>
         </a>
        </a>
        </div>

        <div class="itemdata" >
        <a  href="www.link3" class="frame">
        <img  src='...' />
        </a>
        <a  href="undefined">
         <a  href="www.link1">
          <a  href="www.link1">
            <span class="wlt_shortcode_TITLE">Title 3</span>
          </a>
         </a>
        </a>
        </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

你非常接近。您正在使用.add而不是.find。如果您只是修改它可以正常工作:

jQuery( ".itemdata" ).each(function() {
    var lk = jQuery( this ).find(".frame").attr("href");
    jQuery(this).find(".wlt_shortcode_TITLE" ).wrap("<a href='" + lk + "'></a>");
});

请参阅小提琴:http://jsfiddle.net/rmf7yu7d/