我正在开发一个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有办法做到这一点吗?
答案 0 :(得分:0)
我找到了一种查看链接中单击哪个字符的方法。这也将带您进入已设置的网页
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)
})