用jQuery附加内容 [英] Appending content with jquery

查看:72
本文介绍了用jQuery附加内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们要附加一个错误通知html/css窗格/div,以显示从ajax调用返回到服务器代码所返回的一些应用程序层错误.我们根据来自服务器的json响应有效载荷中是否存在错误进行分支,然后执行以下操作:

Say we are attaching an error notification html/css pane/div to display some application layer errors returned from an ajax call out to server code. We branch on the presence of errors in the json response payload from the server and do the following:

$('#message').remove();
$('body').append('<div id="message" style="display: none;"><a href="" id="message-close">Close</a></div>');
$('#message-close').before(data['message'] + '<ul id="errors"><li>' + data['errors'].join('</li><li>') + '</li></ul>');
$('#message').addClass('error').fadeIn();

这很好用,但是如果人们能指出我可能错过的改进(基本的或使之更加优雅)或jquery方面的缺陷,我将不胜感激.例如,用jQuery散布html片段可能被认为是令人遗憾的.顺便说一下,在其他地方(以及成功分支)定义了#message-close的单击处理程序,因为这是一个经过编辑的示例.如果此问题属于代码检查站点,而不是stackoverflow站点,请告诉我.我没有使用过前者,但知道它存在.

This works just fine, but I would appreciate if people could point out improvements (basic or to make more elegant) or flaws on the jquery side that I might have missed. For instance, interspersing html fragments with jquery could be considered regrettable. By the way there is a click handler for #message-close defined elsewhere (as well as a success branch) as this is a redacted example. If this question belongs on the code review site instead of stackoverflow, please let me know. I haven't used the former, but am aware it exists.

推荐答案

此解决方案绝对不是更简洁,但是我认为程序化方法的扩展性要好一点,并且更适合处理异常和极端情况(当它们不可避免时)出现).

This solution is definitely not more concise, but I think a programmatic approach scales as little bit better and is better suited for handling exceptions and corner cases (when they inevitably show up).

它似乎比使用append然后before的示例更直观.这是自下而上构建的,并在必要时嵌套了数据和事件处理程序.

It also seems to read more straight forward than your example using append then before and so forth. This builds from the bottom up and nests data and event handlers as necessary.

$(function() {

    // simulate ajax call
    setTimeout(function() {

        // ajax datas
        var data = {errors: ['one', 'two', 'three']};

        // close handler
        var closeMessage = function() {
            $(this).parents("div").fadeOut();
            return false;
        };

        // render dialog
        $('<div id="message" style="display: none;"></div>').append(
            $('<ul id="errors"/>').append(
                $.map(data.errors, function(t) {
                    return $("<li/>").text("an error: "+t)[0];
                })))
            .append(
                $('<a href="#close" id="message-close">Close</a>')
                    .click(closeMessage))
            .appendTo("body")
            .fadeIn();

    }, 1000);

});

在jsFiddle上查看其工作原理

这篇关于用jQuery附加内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆