通过 jquery 调用 Web 服务后工具提示 css class 丢失

Tooltip css class lost after web service call via jquery

我有一个 jquery 网络服务影响同一页面上 css class 的工具提示。

问题是这样的;当页面最初加载时,工具提示 css 工作正常,但在通过页面上的按钮调用 Web 服务后,工具提示 class 丢失并显示为标准视图。什么会导致这个?

c# Code Block

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SampleWeb {
  public partial class Sample: System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
      if (!IsPostBack) {
        GetDataForPageLoad();
      }
    }

    public void GetDataForPageLoad() {
      StringBuilder sb = new StringBuilder();

      lblData.Text = string.Format("<a title=\"click to view topic {0}.\" class=\"masterTooltip\"><img width=\"50px\" src='images/Chrysanthemum.jpg' alt=\"{0}\"  /></a><br/>", "XXX");
    }

    [WebMethod]
    public static string GetData() {
      return string.Format("<a title=\"click to view topic {0}.\" class=\"masterTooltip\"><img width=\"50px\" src='images/Chrysanthemum.jpg' alt=\"{0}\"  /></a><br/>", "XXX");
    }
  }
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample.aspx.cs" Inherits="SampleWeb.Sample" %>

  <!DOCTYPE html>

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head runat="server">

    <title>test</title>
    <style type="text/css">
      .tooltip {
        display: none;
        position: absolute;
        border: 1px solid #b83e3e;
        background-color: #d84949;
        border-radius: 5px;
        padding: 5px;
        color: #fff;
      }
    </style>


    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>


    <script>
      function GetData() {

        $.ajax({
          url: 'http://localhost:6878/Sample.aspx/GetData',
          type: 'POST',
          data: '',
          dataType: 'json',
          contentType: 'application/json',
          success: function(data) {

            var obj = document.getElementById("lblData");
            obj.innerHTML = obj.innerHTML + data.d;
          }
        });
      }
    </script>
  </head>

  <body>
    <form id="form1" runat="server">
      <input id="Button1" type="button" value="Get" onclick="GetData();" />
      <br />
      <br />
      <asp:Label ID="lblData" runat="server" Text=""></asp:Label>



      <script type="text/javascript">
        $(document).ready(function() {
          // Tooltip only Text
          $('.masterTooltip').hover(function() {
            // Hover over code
            var title = $(this).attr('title');
            $(this).data('tipText', title).removeAttr('title');
            $('<p class="tooltip"></p>')
              .text(title)
              .appendTo('body')
              .fadeIn('slow');
          }, function() {
            // Hover out code
            $(this).attr('title', $(this).data('tipText'));
            $('.tooltip').remove();
          }).mousemove(function(e) {
            var mousex = e.pageX + 20; //Get X coordinates
            var mousey = e.pageY + 10; //Get Y coordinates
            $('.tooltip')
              .css({
                top: mousey,
                left: mousex
              })
          });
        });
      </script>



    </form>
  </body>

  </html>

我不确定,但我怀疑这一行是你的问题:

obj.innerHTML = obj.innerHTML + data.d;

你用这行连接你的工具提示:

$('.masterTooltip').hover(function() {

它在页面上的所有 .masterTooltip 元素上挂接了一个 hover 处理程序...在那一刻("that moment" 是页面加载并触发 DOM 就绪事件)。

但是当你弄乱一个元素的 innerHTML 时,你实际上是在删除旧元素并用新元素替换它们,因为你还没有将 hover 处理程序连接到这些元素新的,它们不起作用。

如果我是对的,我看到两个可能的解决方案:

1) 将所有 $('.masterTooltip').hover(function() { 代码放在一个函数中。像现在一样调用该函数 onReady,但在 innerHTML 更改后再次调用它以将处理程序连接到新元素

2) 根本不要删除旧元素;而不是使用 innerHTML 替换旧的 lblData 内容:

var obj = document.getElementById("lblData");
obj.innerHTML = obj.innerHTML + data.d;

尝试使用 jQuery 添加一个新元素:

$('#lblData').append('<span>' + data.id + '</span>');
// I'm not even sure the span is needed, but I added it to be safe

sample run before fix

我为接受的解决方案编写了新的代码块,如上所示。

 <script>

        function GetData() {

            $.ajax({
                url: 'http://localhost:27738/WebForm3.aspx/GetData',
                type: 'POST',
                data: '',
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {

                    var obj = document.getElementById("lblData");
                    obj.innerHTML = obj.innerHTML + data.d;


                  
                    //Call RegisterHover
                    $(document).ready(function () {
                        registerHover();
                    });
                }
            });
        }
    </script>
    <form id="form1" runat="server">
        <input id="Button1" type="button" value="Get" onclick="GetData();" /><br /><br />

        <asp:Label ID="lblData" runat="server" Text=""></asp:Label>

        <!--call at ready-->
        <script type="text/javascript">
            $(document).ready(function () {
                registerHover();
            });

            //New function
            function registerHover() {
                // Tooltip only Text
                $('.masterTooltip').hover(function () {
                    // Hover over code

                    // alert("test");

                    var title = $(this).attr('title');
                    $(this).data('tipText', title).removeAttr('title');
                    $('<p class="tooltip"></p>')
                    .text(title)
                    .appendTo('body')
                    .fadeIn('slow');
                }, function () {
                    // Hover out code
                    $(this).attr('title', $(this).data('tipText'));
                    $('.tooltip').remove();
                }).mousemove(function (e) {
                    var mousex = e.pageX + 20; //Get X coordinates
                    var mousey = e.pageY + 10; //Get Y coordinates
                    $('.tooltip')
                    .css({ top: mousey, left: mousex })
                });
            }
        </script>
    </form>