【问题标题】:Jquery append two html pages with different classesJquery附加两个具有不同类的html页面
【发布时间】:2013-12-02 06:09:53
【问题描述】:

您好,我对 jquery 的 .append().html() 函数感到困惑。

我在 AJAX 成功中有这个:

success: function(response){

$('#imodal').html('Success!').addClass("flash-success").fadeIn();

$('#imodal').append(response);

}

这将基本上显示一种 绿色背景中的闪烁消息,其中包含“flash-success”类,以及包含必要信息的来自 JSON 编码的响应关于刚刚发生的交易。

我的问题是,“flash-success”类也出现在附加的响应中。 我如何使这两个课程不同?我试过这个:

$('#imodal').html('Success!').addClass("flash-success").fadeIn();

$('#imodal').append(response).removeClass("flash-success");

但没有运气。附加的响应仍然是绿色的,可能具有“flash-success”类。感谢您的帮助!

【问题讨论】:

  • 你追加到一个容器。容器有一个类。该类将影响附加的内容。混乱在哪里?

标签: javascript jquery html class append


【解决方案1】:

jQuery append() 将在容器末尾插入内容/元素,而不替换其内容。 http://api.jquery.com/append/

在哪里,jQuery html() 将使用给定数据和 html 格式覆盖容器内的内容 http://api.jquery.com/html/

My problem is, the class "flash-success" is also present in the appended response

因为您正在将类添加到附加本身html('Success!').addClass("flash-success")

试试:

$('#imodal').append(response); // Append the child to element
$('#imodal').addClass("flash-success"); // add class to container

【讨论】:

  • 追加或插入新数据不会改变容器的类,除非你已经编码改变。
  • 第一个 html 应该有类,但附加的不应该。我该怎么做?
  • 是的,我明白了,谢谢。我没有多想。我所做的是为 flash 消息添加另一个元素,并为响应添加另一个不同的元素。谢谢
【解决方案2】:

jQuery .append() 方法会将内容添加到元素的末尾。在您的情况下,“响应”将添加到 ID 为“imodal”的 DOM 元素中。

如果您希望在 flash 类之后添加,那么您应该将“响应”附加到位于 flash 类之后的另一个 DOM 元素。

【讨论】:

    【解决方案3】:

    $('#imodal').append(response).removeClass("flash-success"); 这不会从附加响应中删除该类,它会在 #imodal 元素中查找不存在的类。如果您的响应是 html 代码,那么您应该执行以下操作:$(response).removeClass("flash-success");

    【讨论】:

      【解决方案4】:

      只需在附加回复后添加“flash-success”类

      $("#imodal").append(response)
      $("#imodal").addClass("flash-success")
      

      你可以得到你想要的结果----

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-10
        • 2013-05-24
        • 1970-01-01
        • 2019-04-14
        • 1970-01-01
        • 2020-06-06
        • 2016-10-30
        • 2016-04-25
        相关资源
        最近更新 更多