如何超链接进入Json数据的段落中的字符

时间:2016-10-31 04:58:58

标签: html json

问题陈述:

我正在使用Paragraph和LinkLocation获取JSON数据(hiperlink的位置使用LinkLocation的段落中的字符:(6,12))。这意味着,段落中的字符6到字符12我们需要超链接并将其重定向到另一个页面。请告诉我如何做到这一点。

link:{id: 3, index: "Law 1.1", name: "Number of Players ",…}
content:"Law 1.1 shall be replaced by the following."
description:"Law 1.1 shall be replaced by the following:"
id:3
index:"Law 1.1"
ischanged:false
iscollapsed:false
islinked:false
isread:false
linkid:0
linktype:0
name:"Number of Players "
linkposition:"1, 6"

这是我的JSON数据。从这个数据我想按照“Linkposition”超链接“内容”段落。例如,链接位置为“1,6”。所以我想在内容段落中超链接“法律1.1”。

2 个答案:

答案 0 :(得分:1)

如果要超链接字符串中的字符子集,可以这样做:

var data = {
  paragraph: "hello world",
  link: '1,5'
}

var limits = link.split(',');

//subtract one cos substring method is inclusive of bottom limit and exclusive of upper limit
var lowerLimit = limits[0]-1;
var upperLimit = limits[1];

var newParagraph = data.paragraph.substr(0, lowerLimit) + "<a href='otherpage.html'>" + data.paragraph.substr(lowerLimit, upperLimit) + "</a>" + data.paragraph.substr(upperLimit, data.parapgraph.length);

这样会产生结果

<a href='otherpage.html'>Hello</a> world

因此&#39;你好&#39;是超链接

答案 1 :(得分:0)

试试这段代码......我添加了一个可能对您有所帮助的函数addLinksToParagraph(paragraph, linkLocation, location)

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
</head>
<body>
    <script>
        var jsonData = {
            paragraph : 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
            linkLocation : '1,6',
        }

        $('p').html(addLinksToParagraph(jsonData.paragraph, jsonData.linkLocation, "/any_location.html"));

        function addLinksToParagraph(paragraph, linkLocation, location) {

            var splitArray = linkLocation.split(',');

            var start = parseInt(splitArray[0]);
            var end = parseInt(splitArray[1]);

            var preLink = paragraph.substr(0, start);  //part before the hyperlink part
            var link = paragraph.substr(start, end);   //the actual hyperlink part
            var postLink = paragraph.substr(end + 1);  //part after hyperlink part

            console.log(preLink);
            console.log(link);
            console.log(postLink);

            return preLink + '<a href="' + location +'">' + link + '</a>' + postLink;
        }
    </script>
</body>
</html>

这将产生以下输出。

enter image description here