2010-02-23 50 views
3

我对jQuery和JS非常陌生。我需要脚本来扫描一个页面,并用一个包装div来替换任何归类为“圆形”的图像,这样我就可以通过css3应用圆角。我所做的代码完美工作,除非页面上有1个以上的图像,它只是返回第一个图像3次而不是3个单独的图像。使用jQuery替换多次

以下代码 - 非常感谢您的帮助。

var imageWrap = jQuery("img.rounded").attr("src"); 
var imageWrapWidth = jQuery("img.rounded").attr("width"); 
var imageWrapHeight = jQuery("img.rounded").attr("height"); 
var imageWrapAlt = jQuery("img.rounded").attr("alt"); 
jQuery("img.rounded").wrap("<div class='image-wrapper'><p></p>" + "</div>"); 

jQuery(".image-wrapper").css({'background' : 'transparent url('+imageWrap+') no-repeat 0 0','width':imageWrapWidth,'height':imageWrapHeight} ); 
jQuery(".image-wrapper p").text(imageWrapAlt); 
jQuery('img.rounded').hide(); 

回答

4

该代码工作得很好,但是将每个<img>更改为第一个图像。某些功能适用于所有匹配元素,例如csswrap,但某些功能仅适用于的第一个元素- 在这种情况下,这些功能是您希望返回单个值的功能 - attr

你应该使用:

jQuery("img.rounded").each(function(){ 
    var img = jQuery(this); 
    var imageWrap = img.attr("src"); 
    var imageWrapWidth = img.attr("width"); 
    var imageWrapHeight = img.attr("height"); 
    var imageWrapAlt = img.attr("alt"); 

    //next, the '.image-wrapper' selector is also wrong - it selects all new wraps. 
    var wrapper = jQuery("<div class='image-wrapper'><p></p>" + "</div>") 
      .css(
       {'background' : 'transparent url('+imageWrap+') no-repeat 0 0', 
       'width':imageWrapWidth,'height':imageWrapHeight}) 
     .text(imageWrapAlt); 
    img.wrap(wrapper).hide(); 
}); 

参见:

  • .attr() - “找对匹配的元素集合的第一个元素属性的值。”
  • .each()
1

可以使用each功能通过图像采集进行迭代。类似于

jQuery("img.rounded").each(function(){ 
    //$(this) will get you the current image element 
    // save the reference to a variable so that each time you won't have 
    //  to access the DOM element. 
    var currElem = $(this); 
    var imgSrc = currElem.attr("src"); 
}); 
0

当调用“ATTR”来设置这些初始变量,你刚刚从你找到的第一个图像的属性值。

0

看看.each()了解如何将某些东西应用于选择器匹配的所有结果。

0

谢谢大家 - 第一次海报,我会回来宝贵的帮助。 我结束了去这个,它完美的作品 - 再次感谢

jQuery("img.rounded").each(function(){ 
    var img = jQuery(this); 
    var imageWrap = img.attr("src"); 
    var imageWrapWidth = img.attr("width"); 
    var imageWrapHeight = img.attr("height"); 
    var imageWrapAlt = img.attr("alt"); 
    jQuery(this).wrap("<div class='image-wrapper'>" + "<p></p></div>"); 
    jQuery(this).parent().parent().css({'background' : 'transparent url('+imageWrap+') no-repeat 0 0','width':imageWrapWidth,'height':imageWrapHeight}); 
    jQuery(this).parent().text(imageWrapAlt); 
    jQuery(this).hide(); 
});