无法使用jQuery将元素附加到html

时间:2014-11-04 08:21:48

标签: javascript jquery

我想在div中添加所有目的地作为标题,但只添加最后一个。这段代码有什么问题?

<script type="text/javascript">

        $(function() {

            var $dialog = $("#dialog");

            var data = {
                destinations: [
                    {dep: "Varna Airport", dest: "Domodedovo Airport"},
                    {dep: "Domodedovo Airport", dest: "Schwechat"},
                    {dep: "Schwechat", dest: "Heathrow Airport"}
                ]
            };

            $.each(data.destinations, function(key, destination) {

                var $title = $('h1').text(destination.dep + ' - ' + destination.dest);
                $dialog.append($title);
            });
        });

    </script>

 <div id="dialog"></div>

3 个答案:

答案 0 :(得分:5)

您需要使用jQuery创建h1,目前您正在选择h1

使用

$('<h1></h1>')

$('<h1/>')

而不是

$('h1')

&#13;
&#13;
$(function() {

  var $dialog = $("#dialog");

  var data = {
    destinations: [{
      dep: "Varna Airport",
      dest: "Domodedovo Airport"
    }, {
      dep: "Domodedovo Airport",
      dest: "Schwechat"
    }, {
      dep: "Schwechat",
      dest: "Heathrow Airport"
    }]
  };

  $.each(data.destinations, function(key, destination) {

    var $title = $('<h1></h1>').text(destination.dep + ' - ' + destination.dest);
    $dialog.append($title);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dialog"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您将要使用:

var $title = $('<h1 />').text(destination.dep + ' - ' + destination.dest);

为什么?

$('h1')正在设置它可以找到的第一个h1标记的内容到当前字符串,然后将h1移到$dialog
$('<h1 />')实际上会为每次迭代创建一个新的h1,这就是您需要的。

答案 2 :(得分:0)

 <script type="text/javascript">

    $(function() {

        var $dialog = $("#dialog");

        var data = {
            destinations: [
                {dep: "Varna Airport", dest: "Domodedovo Airport"},
                {dep: "Domodedovo Airport", dest: "Schwechat"},
                {dep: "Schwechat", dest: "Heathrow Airport"}
            ]
        };
       var $title = "";
        $.each(data.destinations, function(key, destination) {
              //Edited
            $title += $('<h1 />').text(destination.dep + ' - ' + destination.dest);

        });
        $dialog.append($title);
    });

</script>