2

Total noob here, trying to conditionally append some values to an html object. This is built from sample code I found so be kind...

$.getJSON('url to facebook json feed', function(fbresults){
    $.each(fbresults.data, function(){
        $('<div></div>')
        .append('<h1>' + this.from.name + '</h1>')
        .append('<p>' + this.story + '</p>')
        $if (typeof this.picture !== "undefined") {
            .append('<img src="' + this.picture + '">')};
        .appendTo('#facebook')
          });
     });
4

4 回答 4

3

jQuery 的append方法接受多个元素,包括 null 对象,例如:

$('<div>').append(
    $('<p>').text('First paragraph'),
    $('<p>').text('Second paragraph'),
    null,
    $('<p>').text('Third paragraph')
);

这相当于

$('<div>').append(
    $('<p>').text('First paragraph')
).append(
    $('<p>').text('Second paragraph')
).append(
    null
).append(
    $('<p>').text('Third paragraph')
);

请注意,null在最终的 DOM 元素中将简单地忽略对象。

因此,您可以按如下方式调整代码:

$.getJSON('url to facebook json feed', function(fbresults){
    $.each(fbresults.data, function(){
        $('<div></div>').append(
            $('<h1>').html(this.from.name),
            $('<p>').html(this.story),
            (this.picture) ?
                $('<img>').attr('src', this.picture) :
                null
        ).appendTo('#facebook')
    });
});

附加到的第三个元素divimg元素或null取决于this.picture是否定义。

于 2016-09-30T20:47:27.087 回答
2

您不必将它们全部链接在一起:

$.getJSON('url to facebook json feed', function(fbresults){
    $.each(fbresults.data, function(){
        var element = $('<div></div>');
        element.append('<h1>' + this.from.name + '</h1>');
        element.append('<p>' + this.story + '</p>');

        if (typeof this.picture !== "undefined") {
            element.append('<img src="' + this.picture + '">')
        };
        element.appendTo('#facebook');
    });
});

构建您想要在字符串中附加的内容并将其附加在 $.each 之后也被认为是一种很好的做法

于 2013-03-03T23:02:10.330 回答
1

jQuery 只是一个 JavaScript 库。您仍在使用 JavaScript:

$.getJSON('url to facebook json feed', function(fbresults){
    $.each(fbresults.data, function(){
        var $div = $('<div>');

        $('<h1>', {text: this.from.name}).appendTo($div);
        $('<p>', {text: this.story}).appendTo($div);

        if (this.picture) {
            $('<img>', {src: this.picture}).appendTo($div);
        }

        $div.appendTo('#facebook');
     });
});
于 2013-03-03T22:59:45.557 回答
0

尝试这样的事情:

$.getJSON('url to facebook json feed', function(fbresults){
    $.each(fbresults.data, function(){
        var $wrapper = $('<div></div>')
            .append('<h1>' + this.from.name + '</h1>')
            .append('<p>' + this.story + '</p>');

        if (this.picture) {
            $wrapper.append('<img src="' + this.picture + '">');
        } else {
            $wrapper.appendTo('#facebook');
        }
    });
});
于 2013-03-03T23:00:43.797 回答