将data-attribute添加到附加对象src

时间:2014-10-03 16:09:52

标签: javascript jquery

我想附加一个链接到多个列表项,这些列表项将data-attribute传递给URL的末尾。但是我不明白如何使变量“storyId”为.Story的每个实例保持不同的值

<div id="InnerPage">
  <ol>
    <li class="Story" data-id="35213">Text for Link 1 </li>
    <li class="Story" data-id="35204">Text for Link 2 </li>
  </ol>
</div>

<script>
  var storyId = this.getAttribute('data-id');
  var sidebarURL = "'index.html?storyid=' + storyId"
  var newA = document.createElement('a');
  newA.setAttribute('href',sidebarURL);
  newA.innerHTML = "Split View";

  $('.Story').append([newA]);
</script>

应该导致:

<div id="InnerPage">
  <ol>
    <li class="Story" data-id="35213">Text for Link 1 <a href="index.html?storyid=35213">Split View</a></li>
    <li class="Story" data-id="35204">Text for Link 2 <a href="index.html?storyid=35204">Split View</a></li>
  </ol>
</div>

http://jsfiddle.net/s3wtsxw5/

1 个答案:

答案 0 :(得分:0)

你可以这样做:

$("#InnerPage ol li").each(function() {
    var id = $(this).data("id");
    var link = "index.html?storyid=" + id;
    $(this).append("<a href='" + link + "'>Split View</a>");
});