【问题标题】:jQuery "each" methodjQuery“每个”方法
【发布时间】:2013-01-09 21:42:54
【问题描述】:

我是一名 javascript 初学者,但在使用 jQuery 的“each”方法时遇到了一些问题。我在一个 Joomla 网站上有一个画廊模块,用作简单的图像滑块。我添加了一些代码以允许链接图像上的灯箱。我现在想做的是将缩略图标题(模块当前添加的)复制到链接中的 Title 属性,以便它显示在每个图像的灯箱中。

HTML 的结构如下...

<div class="camera_wrap" id="camera_wrap_106">
<div class="cameraContents">
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
    <div class="cameraContent">
        <a class="camera_link" href="lightbox-large.jpg" title="This is where i need the caption"></a>
        <div class="camera_caption">
            <div>This is the caption</div>
        </div>
    </div>
</div>

到目前为止,我已经获得了代码,但它仅将第一个标题 div 复制到每个标题属性,而不是在每个实例上执行它。不确定这是否是最好的开始......

$("#camera_wrap_106 .cameraContent").each(function() {
    $("#camera_wrap_106 a.camera_link").attr('title', $("#camera_wrap_106 .camera_caption div").html());
});

提前致谢!

【问题讨论】:

    标签: jquery loops each


    【解决方案1】:

    可以使用attr()的回调函数

    $("#camera_wrap_106 .cameraContent a.camera_link").attr('title',function(){
        return $.trim($(this).next().text());
    });
    

    http://jsfiddle.net/nSj8h/

    或者,如果您想使用每个语句,只需在选择器中设置 context

    $("#camera_wrap_106 .cameraContent").each(function() {
        $("a.camera_link",this).attr('title', $(".camera_caption div",this).text());
    });
    

    在选择器中添加上下文与使用 find 是一回事

    $('element',context) == $(context).find('element')
    

    http://jsfiddle.net/baLmn/

    【讨论】:

      【解决方案2】:

      你应该使用this

      $("#camera_wrap_106 .cameraContent").each(function() {
          $(this).attr('title', $(this).html());
      });
      

      .each 提供迭代中的元素作为函数的上下文(即this)。

      它也作为第二个参数提供(第一个是索引),这意味着你也可以这样写:

      $("#camera_wrap_106 .cameraContent").each(function(index, element) {
          $(element).attr('title', $(element).html());
      });
      

      【讨论】:

      • $("#camera_wrap_106 .cameraContent").attr("title", function () { return $(this).html(); });
      • @Tomalak 对。即使它没有解释 .each 在这种情况下显然是更清洁的解决方案。
      • 感谢您的建议。但是,给出的代码正在做同样的事情。由于某种原因,它仍在将第一个标题 div 复制到每个 Title 属性。
      • 你确定吗?我不明白这怎么可能。难道你没有缓存问题。
      猜你喜欢
      • 2012-07-19
      • 2010-12-26
      • 1970-01-01
      • 2011-07-27
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      相关资源
      最近更新 更多