简体   繁体   中英

detect which word has been clicked inside link

I'm working on a chrome extension that extracts every word clicked. This code works great for any word outside of a link:

 $(document).click(function(e) { var t = ''; var s = window.getSelection(); if (s.isCollapsed) { s.modify('move', 'forward', 'character'); s.modify('move', 'backward', 'word'); s.modify('extend', 'forward', 'word'); t = s.toString(); s.modify('move', 'forward', 'character'); } else { t = s.toString(); } console.log(t); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#">foo bar</a><br> words not in link

However I also need to get the words clicked inside a link. so for example with this html:

<a href="#">foo bar</a>

I need to get "foo" when the word foo is clicked. Is there a way do to that with jQuery?

I found a way to see which character is clicked within a link. This also takes you to the webpage you have set for it to go to

var link = prompt('what would you like as a link');
var href = prompt("where would you like the link to go")
var splitLink = link.split('');
for(var i = 0;i<splitLink.length;i++){
  $('body').append('<a target="_blank">'+splitLink[i]+"</a>");
}
$('a').click(function(){
  alert('you clicked the '+$(this).html());
  window.open(href)
})

and if you wish you can also do this for multiple words if you wish to see which word is clicked

var link = prompt('what would you like as a link');
var href = prompt("where would you like the link to go")
var splitLink = link.split(' ');
for(var i = 0;i<splitLink.length;i++){
  $('body').append('<a target="_blank">'+splitLink[i]+" </a>");
}
$('a').click(function(){
  alert('you clicked the '+$(this).html());
  window.open(href)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM