【问题标题】:detect which word has been clicked inside link检测链接内点击了哪个单词
【发布时间】:2019-12-03 00:55:59
【问题描述】:

我正在开发一个 chrome 扩展程序,它可以提取每个点击的单词。此代码适用于链接之外的任何单词:

$(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

但是,我还需要点击链接中的单词。所以例如这个html:

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

当点击单词 foo 时,我需要得到“foo”。有没有办法用 jQuery 做到这一点?

【问题讨论】:

  • 也许你可以实现一些正则表达式来替换 s.toString() 之后的所有 HTML?
  • 非常有趣的问题。我不知道如何做到这一点,但这篇文章的答案中的 JSFiddle - stackoverflow.com/questions/43571090/… 很有希望。我在 Chrome(左键单击)中对其进行了测试,它正确地显示了每个单词。假设该示例不在锚标记内,它可以为您提供一些见解
  • 不幸的是 window.getSelection();当您单击“a”之类的链接标签时,不会捕获选择,除非“a”标签没有“href”属性。

标签: javascript jquery


【解决方案1】:

我找到了一种查看链接中点击了哪个字符的方法。这也会将您带到您为其设置的网页

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)
})

如果您希望查看点击了哪个单词,也可以对多个单词执行此操作

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)
})

【讨论】:

    猜你喜欢
    • 2011-11-25
    • 2012-04-17
    • 2016-02-08
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多