如何在jQuery中构造一个新的HTML元素?

时间:2015-09-16 21:04:26

标签: javascript jquery html functional-programming chaining

我有一些类似的代码:

var glyph = isApple ? '<span class="glyphicon glyphicon-apple"></span>' : '<span class="glyphicon glyphicon-banana"></span>';
var newFruit = '<li class="list-group-item">' + glyph + '<span class="badge">' + score + '</span>' + name + '</li>'
$('#fruitList').append(newFruit);

很多粗俗的连接很难阅读和遵循。有没有办法在功能上创建这些元素,如果是这样,如何?此外,我很好奇这样做的速度,因为如果它比我正在做的慢得多,那么我就不会打扰了。

我正在寻找类似的东西,例如:

var newElement = li().class("list-group-item").value(name);
newElement.span().class(isApple ? "glyphicon glyphicon-apple" : "glyphicon glyphicon-user");
newElement.span().class('badge').value(score);
$('#fruitList').append(newElement);

现在很明显,上述情况并不好,甚至可能是正确的,但希望它可以解决这个问题。基本上是一种链接函数来创建新元素的方法,这些元素可以避免创建用于插入的自定义HTML的连接混乱。

5 个答案:

答案 0 :(得分:1)

这样的东西?

$('<li>', {
        html: $('<a>', {
             href: item.href,
             text: item.title
        })
    });

这会在a标记中添加li标记。您可以根据需要进行修改

答案 1 :(得分:1)

这个结构应该有所帮助,诀窍是确保在子元素之前附加父元素:

var newElement = document.createElement('li');
$(newElement).addClass('list-group-item');
$(newElement).html(name);

$('#fruitList').append(newElement);

var newSpan = document.createElement('span');
var apple = isApple ? "glyphicon glyphicon-apple" : "glyphicon glyphicon-user";
$(newSpan).addClass(apple);
$(newSpan).addClass('badge');
$(newSpan).html(score)

$(newElement).append(newSpan);

答案 2 :(得分:0)

var $li = $("<li/>",{title:"woot"}).addClass("list-group-item").value(name);
$li.append( $("<span/>").addClass(isApple ? "glyphicon glyphicon-apple" : "glyphicon glyphicon-user") );
$("<span/>").addClass('badge').value(score).appendTo( $li );
$('#fruitList').append($li);

答案 3 :(得分:0)

一般来说,数组比字符串连接更快,这比DOM操作更快。

function getNewItemString(glyph,score,name){
   return [
      '<li class="list-group-item">',
      '<span class="glyphicon ',
      glyph,
      '"></span>',
      '<span class="badge">',
      score,
      '</span>',
      name,
      '</li>'
   ].join('');
}

$('#fruitList').append(getNewItemString('glyphicon-apple', 20, 'player1'));
$('#fruitList').append(getNewItemString('glyphicon-banana', 0, 'player2'));

答案 4 :(得分:0)

an overload of the jQuery function允许您创建元素并指定其属性。以下将复制您的示例:

$('<li>', {
    class: "list-group-item",
    html: $('<span>', {
        class: isApple ? "glyphicon glyphicon-apple" : "glyphicon glyphicon-user"
    })
    .after($('<span>', {
        class: "badge",
        text: score
    }))
    .after(name)
});