在这里,我给你写了一些东西让你开始。它比您的原始代码更具跨浏览器:
(function(AnchorSelector, $, undefined) {
AnchorSelector.getAnchorHrefs = function(e) {
var container = '';
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var div = $('<div>');
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
div.append(sel.getRangeAt(i).cloneContents());
}
container = div;
}
} else if (document.selection) {
container = $('<div>').append(document.selection.createRange().htmlText);
}
var arr = $.map(container.find('a'), function(n, i) {
return ($(n).attr('href'));
});
if (arr.length) {
alert(arr.join(','));
}
// Note: you can check e.type to see if it was a 'dblclick' or a 'mouseup'
// you may need to employ some type of debouncing to not get two alerts
// when you double click the text
}
$(function() {
$(document)
.dblclick(AnchorSelector.getAnchorHrefs)
.mouseup(AnchorSelector.getAnchorHrefs);
});
})(window.AnchorSelector = window.AnchorSelector || {}, jQuery);
这是一个jsFiddle 演示。