无法使用jQuery动态添加超链接?

时间:2016-05-24 17:32:57

标签: javascript jquery

我想以这种方式使用jquery将href添加到<a>

$(document).ready(function() {
  var links = [
  {
    "_id": "57448a261f3e6161b34739f2",
    "index": 0
  },
  {
    "_id": "57448a2663568bbfc9dafe74",
    "index": 1
  },
  {
    "_id": "57448a26db2fbfa5cd38731f",
    "index": 2
  },
  {
    "_id": "57448a2650e28fbe8e2d87b3",
    "index": 3
  },
  {
    "_id": "57448a26a5e9ec8bd78c9809",
    "index": 4
  },
  {
    "_id": "57448a26fa772d6314ddc059",
    "index": 5
  },
  {
    "_id": "57448a26ba5a1782ae7c14af",
    "index": 6
  }
];

  for(var i in links){

    $('#link-list').append(
        $('<li>').append( 
          $('<span>').append(
          $('<a href="https://www.my-domain.so/goto?link-id="'+i+'></a>').html(i)
            ),
          $('</span>')
        ),
        $('</li>')
    );

  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<ul id="link-list"></ul>

我希望结果为

https://www.my-domain.so/goto?link-id=0
https://www.my-domain.so/goto?link-id=1
.
.
.
https://www.my-domain.so/goto?link-id=n

徒劳,请提出正确的方法。

2 个答案:

答案 0 :(得分:0)

您的代码中存在错误的databinding { enabled = true } ,在连接"之前,您已关闭href标记。

i

还有另一个错误,您使用的$('<a href="https://www.my-domain.so/goto?link-id='+i+'"></a>').html(i) // moved to here--------^------------- $('</span>')不是有效的选择器或html创建者。我想你正试图附上标签。实际上,没有必要访问更多信息:http://api.jquery.com/jquery/#jQuery-html-attributes

检查更新后的代码段

&#13;
&#13;
$('</li>')
&#13;
$(document).ready(function() {
  var links = [{
    "_id": "57448a261f3e6161b34739f2",
    "index": 0
  }, {
    "_id": "57448a2663568bbfc9dafe74",
    "index": 1
  }, {
    "_id": "57448a26db2fbfa5cd38731f",
    "index": 2
  }, {
    "_id": "57448a2650e28fbe8e2d87b3",
    "index": 3
  }, {
    "_id": "57448a26a5e9ec8bd78c9809",
    "index": 4
  }, {
    "_id": "57448a26fa772d6314ddc059",
    "index": 5
  }, {
    "_id": "57448a26ba5a1782ae7c14af",
    "index": 6
  }];

  for (var i in links) {
    $('#link-list').append(
      $('<li>', {
        html: $('<span>', {
          html: $('<a>', {
            href: "https://www.my-domain.so/goto?link-id=" + links[i].index,
            text: i
          })
        })
      })
    );
  }

});
&#13;
&#13;
&#13;

您可以看到这些代码与以下图片的区别

enter image description here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <ul id="link-list"></ul>只返回一个空的jQuery对象,其中$('</span>')充当选择器。 </span>(或$('<span>'))创建一个包含结束标记本身的新元素。您还可以使用$('<span/>')创建元素。有关creating new elements using jQuery visit here的更多信息。

答案 1 :(得分:-1)

尝试这种代码安静..

https://jsfiddle.net/prasadraja07/qopbw0n2/

 for (var i in links) {
            $("<li/>")
        .append($("<span/>")
        .append($("<a/>").attr({ "href": "https://www.my-domain.so/goto?link-id=" + links[i]._id }).html(links[i].index)))
      .appendTo("#link-list");           
        }
相关问题