简体   繁体   English

如何清理此jQuery hover + wrap函数

[英]How to clean up this jQuery hover+wrap function

Here's my function: 这是我的功能:

var add_cloud_zoom_wrapper = function() {
  $('#main-image').hover(function() {
    $('#main-image').wrap(function() {
      return '<a href=' + $(this).attr('src').replace(/\bproduct\b/, 'original') + ' class="cloud-zoom" id="zoom1" rel="adjustX: 10, adjustY:-4, position: \'inside\'">';
    });
  });
}

The .wrap() alone works. .wrap()单独有效。 I need this to work however, whenever the image is hovered over because I have another event where the image changes, so I'll need a new anchor tag to hover the newly embedded image each time. 但是,无论何时将鼠标悬停在图像上,我都需要这样做,因为在另一个事件中图像发生了更改,因此每次都需要一个新的定位标记来悬停新嵌入的图像。 The other part of this is I need to remove the anchor tag with id="zoom1" before I wrap, otherwise we'll have additional/broken markup. 这的另一部分是,在包装之前,我需要删除id =“ zoom1”的锚标记,否则我们将获得额外的/损坏的标记。 What's the best way to clean this up? 清理此事的最佳方法是什么?

My HTML is straight forward: 我的HTML很简单:

<img alt="foo" id="main-image" src="/assets/products/1051/product/Perspective_View-0.jpeg?1290039436" />

I'm not 100% sure I understood your question, but this may work: 我不确定100%是否了解您的问题,但这可能有用:

var add_cloud_zoom_wrapper = function() {
    $('#main-image').hover(
    function() {
        $(this).wrap(function() {
            return '<a href=' + $(this).attr('src').replace(/\bproduct\b/, 'original') + ' class="cloud-zoom" id="zoom1" rel="adjustX: 10, adjustY:-4, position: \'inside\'">';
        });
    }, function() {
        var link_element = $(this).closest('a');
        link_element.parent().append($(this));
        link_element.remove();
    });
};

You can see it working here . 您可以看到它在这里工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM