如果您不想事先将每个单词都包含在标签中,则可以在单击后尝试这样做。如果您有单独的段落,则只需转换用户在其中单击的段落。
例如(http://jsfiddle.net/scovetta/TU9rs/1/)
$('#paragraph').live('click', function($evt) {
var original_text = $(this).text();
var word_list = $(this).text().split(' ');
var word_html = '';
// Convert each word to an individual span
$.each(word_list, function(_, word) {
word_html += '<span class="word">' + word + '</span> ';
});
// Replace original paragraph with the spans
$(this).text('').html(word_html);
// Search through each span for one in the right spot
$('#paragraph .word').each(function(_, elt) {
var rect = elt.getBoundingClientRect();
if ($evt.pageX >= rect.left &&
$evt.pageY >= rect.top &&
$evt.pageX <= rect.right &&
$evt.pageY <= rect.bottom) {
alert('You clicked on the word: ' + $(elt).text());
return;
}
});
// Clean up after ourselves
$(this).html('').text(original_text);
});
</p>