如何添加不同的超链接数据*?

时间:2016-08-07 09:31:07

标签: javascript

我有以下HTML代码:

<article class="article" data-quota="Here goes nothing" data-share="Here goes social" data-tag1="Tag1" data-tag2="Tag2" data-tag3="Tag3">
  <h3>Author name</h3>
</article>

和JS:

function articleTemplate() {
  $('.article').each(function() {

    var $this = $(this),
        dataQuota = $this.data('quota'),
        dataTag1 = $this.data('tag1'),
        dataTag2 = $this.data('tag2'),
        dataTag3 = $this.data('tag3'),
        dataShare = $this.data('share');

    var template =  '<h4>' + dataQuota + '</h4>' +
                    '<h5>' + dataTag1 + ',' + dataTag2 + ',' + dataTag3 + '</h5>' +
                    '<footer>' + dataShare + '</footer>';

    $this.append(template);
  });
}

我正在用javascript做一些模板,直到现在我得到了这个。 输出的html是:

<h3>Author name</h3>
<h4>Here goes nothing</h4>
<h5>Tag1,Tag2,Tag3</h5>
<footer>Here goes social</footer>

现在我想添加数据配额,数据共享,data-tag1等的超链接?

2 个答案:

答案 0 :(得分:0)

你有多么不同的选择。一个是这样写的:

<article class="article" data-quota-content="Here goes nothing" data-quota-href="/some/link">
  <h3>Author name</h3>
</article>

jQuery会自动将数据转换为嵌套对象。

等效的解决方案是将JSON格式的字符串放入属性中,这也将自动解析:

<article class="article" data-quota='{"content":"Here goes nothing", "href":"/some/link"}'>
  <h3>Author name</h3>
</article>

所以如果你写:

 var $this = $(this),
     dataQuota = $this.data('quota')

然后dataQuota将是一个包含以下内容的对象:

{
   content : "Here goes nothing",
   href : "/some/link"
}

你可以这样使用它:

var template =  '<h4><a href="'+dataQuota.href+'">' + dataQuota.content + '</a></h4>' +

作为一个注释,您不应该像上面那样创建HTML代码,更好的方法是以这种方式创建它:

$this.append( 
   $('<h4>').append(
       $('<a>')
          .attr('href',dataQuota.href)
          .text(dataQuota.content)
   )
);

这可确保您不会遇到转义问题。

答案 1 :(得分:0)

只是一些简单的推文到js文件:

function articleTemplate() {
    $('.article').each(function() {

        var $this = $(this),
            dataQuota = $this.data('quota'),
            dataTag1 = $this.data('tag1'),
            dataTag2 = $this.data('tag2'),
            dataTag3 = $this.data('tag3'),
            dataShare = $this.data('share');

        var template =  '<h4><a href="' + url + '">' + dataQuota + '</a></h4>' +
                        '<h5><a href="' + url2 + '">' + dataTag1 + '</a>,' + dataTag2 + ',' + dataTag3 + '</h5>' +
                        '<footer>' + dataShare + '</footer>';

        $this.append(template);
    });

}

var url = "http://bencollier.net/";
var url2 = "http://google.ro/";
相关问题