2016-10-31 27 views
1

問題陳述:如何超鏈接款這在JSON數據來的字符

我得到一個JSON數據與段落和LinkLocation(位置在使用LinkLocation段落hiperlink的特點:(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數據。從這個數據我想超鏈接的「內容」段落「鏈接」。例如這裏的鏈接位置是「1,6」。所以我想在內容段落中超鏈接「Law 1.1」。

+0

所以是這樣的: 數據 - > {段:你好,鏈接:1-4} ,你想發送到另一個頁面: 數據 - > {款:H ell那裏}? – Jayce444

+0

如果段落類似「Hello world」,鏈接數據爲1,5,那麼「Hello」應該超鏈接,我必須在那裏給出鏈接,我應該在那裏重定向。 – Sriram

+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 

因此「你好」超鏈接

+0

工作兄弟,感謝您的幫助 – Sriram

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

+0

工作兄弟,感謝您的幫助 – Sriram

相關問題