0

我正在设置一个具有以下功能的页面:

  1. 向用户显示 5 张图像。
  2. 一些视觉效果绑定到图像。
  3. 如果用户滚动到页面底部,则会加载另外 5 个图像。
  4. <div>使用.html()函数更新容器的 Html 。
  5. 视觉效果与新的 5 幅图像绑定。

视觉效果是使用Image Mapster突出显示图像的一些预定义区域。

问题:

添加新的五张图像后,所有先前图像的视觉效果都消失了。

问题:

调用该.html()函数是否会删除先前在现有 上设置的绑定html

如何在html不删除以前设置的绑定的情况下更新?

这是代码的简化版本:

向下滚动时是否到达页面底部的代码检查:

$(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
        console.debug("_____________ DEBUG _____________: reached bottom()");
        // check if there are images to load, if so call Visualize()
        if ( there are more images to load in a buffer)
            ShowMore();
        }
    }
});

代码显示另外 5 张图片:

function ShowMore() {
  console.debug("_____________ DEBUG _____________: in /ShowMore()");
  
  // get the html of the image container div
  old_html = $('#image_result_container').html();

  // ajax request to get the 5 more images from server
  $.ajax({
    url: "/GetImages/",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({'visualize_ids': visualize_ids}),
    dataType: "json",
    success: function( response ) {

      // some complex manipulation that creates the html for the 5 images just loaded
      new_html = old_html + <div>...some stuff in here...</div>

      // I set the html of the container to the new html
      $('#image_result_container').html(new_html);

      // this part calls the ImageMapster function only on the last 5 images using an id value that I won't explain for conciseness reasons...
      for (i = 0; i < 5; i++) {
        ImageMapster( some_id, i );
      }
  });
}

ImageMapster()函数所做的基本上是将可视化函数绑定到图像元素:

var map = $('#vis_image_' + ann_id + '_' + im_count_id);
map.mapster({ all the cool effects go here... });

我在代码下方附上了视觉效果(为了完整性),但这对于这个问题并不重要。

视觉效果代码:

function ImageMapster( ann_id, im_count_id ) {
  console.debug("_____________ DEBUG _____________: in /ImageMapster()");
  console.debug(" $> ann: [" + ann_id + "] im_count: [" + im_count_id + "]");
  var map = $('#vis_image_' + ann_id + '_' + im_count_id);
  map.mapster({
    areas: [
    {
      key: 'subject',
      staticState: true,
      fillColor: '6699ff',
      fillOpacity: 0.4,
      stroke: true,
      strokeColor: '6699ff',
      strokeWidth: 3
    },
    {
      key: 'object',
      staticState: true,
      fillColor: '8ae65c',
      fillOpacity: 0.4,
      stroke: true,
      strokeColor: '8ae65c',
      strokeWidth: 3
    }
    ],
    mapKey: 'name'
  });
}
4

3 回答 3

2

jQuery 选择器的工作方式是在代码运行时绑定到匹配项。当删除选择器匹配的HTML时,绑定在匹配确切代码时的绑定也是如此。不是图案。

处理此问题的最短方法是使用 jQuery(selector).append() 在元素末尾添加新代码,而不是通过 .html() 替换所有内容。这样,您以前的活页夹将结转。

http://api.jquery.com/append/

于 2015-10-20T18:43:26.903 回答
0

您可以使用 Jquery element.clone(true,true); 显然对您现有的代码进行了一些更改,这应该很容易工作。

于 2015-10-20T19:15:26.507 回答
0

$().html()销毁元素,然后创建新元素。绑定在旧的(现已销毁)元素上。如果使用 . 则需要重新绑定$().html()您可以通过不使用$().html()而是使用$().detach()$().attach()反对现有元素来绕过重新绑定。

于 2015-10-20T19:05:58.357 回答