【问题标题】:How to add static HTML before and after jquery prependTo inside $.each如何在 $.each 中的 jquery prependTo 之前和之后添加静态 HTML
【发布时间】:2016-10-19 00:58:55
【问题描述】:

我有数组和循环遍历 jQuery $.each 来迭代和动态创建 html dom 元素并将其添加到 DOM。

  $.each(res, function(key, ele){
        var stemtext = ele[0];
        var stemID = ele[1];
        var pageNo = ele[2];            
        //Build HTML here
        $('<div/>', {
            'id':stemID,
            'class':'text-paragraph',
            'style':'cursor:pointer;',
            'html': '<p style="width: 80%; float: left;">'+ stemtext +'</p><p style="width:20%; float:left">'+ stemID +'</p>'
        }).prependTo('#PlaceHolder');
    });

这段代码完美无缺。

但我需要在 $.each 循环中生成的 HTML 之前和之后添加一些静态 HTML,然后添加它。我只能在 jQuery 中执行此操作,不能触摸 HTML。

我尝试将这个 html 存储到一个变量中,然后添加 HTML,但没有奏效,

在 $.each 循环中生成的 HTML 前后添加一些静态 HTML 的最佳方法是什么?

【问题讨论】:

  • 您要添加什么 HTML? before()after()insertBefore()insertAfter() 将根据您的需要工作。
  • 哦..就这么简单..让我试试。这是我试图在

    问题文本

    选项选择

标签: javascript jquery html foreach each


【解决方案1】:

我不知道我是否遇到了您的问题,但根据我的理解,有我的解决方案(我确信有更好的方法):

 $('<div/>', {
        'id':"todelete",
    }).prependTo('#PlaceHolder');


   $('<div/>', {
        'id':"stemID",
        'class':'text-paragraph',
        'style':'cursor:pointer;',
        'html': '<p style="width: 80%; float: left;">stem text</p><p style="width:20%; float:left">stemID</p>'
    }).prependTo('#todelete');

    $('<div/>', {
        'id':"elementBefore",
        'class':'text-paragraph',
        'style':'cursor:pointer;',
        'html': '<p>Before place holder</p>'
    }).prependTo('#todelete');

    $('<div/>', {
        'id':"elementAfter",
        'class':'text-paragraph',
        'style':'cursor:pointer;',
        'html': '<p >After place holder</p>'
    }).appendTo('#todelete');

    $("#stemID").unwrap();

现场演示JSFiddle

【讨论】:

    猜你喜欢
    • 2013-05-07
    • 2018-02-07
    • 2019-11-12
    • 2012-05-29
    • 2012-08-26
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多