jquery - 当 img 附加到 div 时工具提示不起作用

标签 jquery html css

我正在使用工具提示将图像附加到 div,但工具提示不适用于 div 中的图像。我在 div 之外有一个静态图像,为此工具提示正在工作。

下面是 jquery 函数的一个异常(exception):

success: function (result) {
  if (result != null) {
    var MyPics = result.MyIctures;
    $.each(MyPics, function (index, value) {
      var im = (MyPics[index].FILE_PATH);
      console.log(MyPics[index].file_date);
      var img = $("<img />");
      img.attr("id",""+ MyPics[index].file_path+"");
      img.attr("style", "height:100px;width: 100px");
      img.attr("data-toggle", "tooltip");
      img.attr("data-html", "true");
      img.attr("data-placement", "top");
      img.attr("title", "<em>Title:" + MyPics[index].file_name + "</em> <hr> <b></b>");
     img.addClass("img_preview");
     img.attr("src", im);
     $("#mypics").append(img);
     // console.log(im);
     //   
     }
   )
  }
}

此 img 的工具提示有效,但附加到 div 的工具提示无效。

<img id="bing_img_dessc" class="img_preview" style="height:50px" data-toggle="tooltip" data-html="true" data-placement="top" title="<em>sss</em> <hr> <b>sss</b>" src="~/Resources/Images/login-user-icon.png">  

任何建议都会有所帮助。谢谢。

最佳答案

问题是因为您仅在页面加载时调用 tooltip(),因此只有此时存在于 DOM 中的元素才会在悬停时显示工具提示。要解决此问题,您还需要在添加新图像时调用 tooltip():

success: function(result) {
  if (!result)
    return;

  var images = result.MyIctures.map(function(image) {
    return $('<img />', {
      'id': image.file_path,
      'data': {
        'toggle': 'tooltip',
        'html': 'true',
        'placement': 'top'
      },
      'title': '<em>Title:' + image.file_name + '</em><hr>',
      'class': 'img_preview',
      'src': image.FILE_PATH
    });
  });

  $("#mypics").append(images).find('.img_preview').tooltip();
}

请注意,我通过使用 map() 构建一个仅附加一次的 jQuery 对象数组来整理逻辑以使其更简洁。

另请注意,您同时使用了 FILE_PATHfile_path 属性;确保这是正确的,因为 JS 区分大小写。 MyIctures 也应该是 MyPictures

关于jquery - 当 img 附加到 div 时工具提示不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57408033/

相关文章:

jquery - 脚本导致链接有时间延迟

javascript - 多个文件上传 - 带有 'remove file' 链接

javascript - 如何在滚动页面顶部附近制作一个 div?

javascript - 在javascript中拖动光标?

css - Bootstrap Modal 无法滚动

javascript - 位置固定 y 轴仅在可滚动的 div 内

javascript - 如何防止div滚出页面

javascript - 使用缓存破坏时,缓存文件会发生什么情况?

javascript - 如何在短时间内用IE删除很大一部分的DOM?

javascript - 窗口调整大小功能不起作用