问题
I was looking through stackoverflow and came across this link(How to get a word under cursor using JavaScript?)
They has the code:
<p>Each word will be wrapped in a span.</p>
<p>A second paragraph here.</p>
Word: <span id="word"></span>
<script type="text/javascript">
$(function() {
// wrap words in spans
$('p').each(function() {
var $this = $(this);
$this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});
// bind to each span
$('p span').hover(
function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
function() { $('#word').text(''); $(this).css('background-color',''); }
);
});
</script>
When I tried this out, I realized this code will only work with paragraph tags. How should I edit the Javascript/Regex of this code to make it work will all tags(h1,h2,h3)?
Thanks in advance!
回答1:
jsFiddle Demo
Make a few adjustments. Change the selector to include h1,h2,h3
$('p,h1,h2,h3').each(function() {
And then also do this lower for the hover. You will need to use find
on the set for the nested spans.
$('p,h1,h2,h3').find("span").hover(
来源:https://stackoverflow.com/questions/20805512/identify-word-on-javascript-onhover