开发者

jquery get selected word

i have a div with class='divclass' and some text inside it... now i want to display a popup when the user mouseover any word inside div... the popup will also display the word on 开发者_如何学JAVAwhich user has mousedover the mouse... how can we achieve this?..


i think you have to surround any word with an element like <span> and then:

$('.divclass span').mouseover(function(){
    alert($(this).text());
    // or showMyPopup($(this).text());
});


I agree with bicccio. To save time you could also automate the span creation around each word with the following code, and then attach the event to display the text:

$(function() {
    var text = $(".divclass").text();
    text = "<span>" + $.trim(text) + "</span>";
    text = text.replace(/\s/g, "</span><span>&nbsp;")
    $(".divclass").html(text);

    $(".divclass span").live("mouseover", function() {
        alert($(this).text());
    });
});


Try this:

$(document).ready(function(){
var all_words=$("#divclass").text().split(' ');
$("#divclass").html("");

$.each(all_words, function(i,val)
{
$('<span/>').text(val +" ").appendTo("#divclass");

});
$("#divclass span").live("mouseover",function(){
    alert($(this).text());
});

});

See it live here: http://jsfiddle.net/jqLw8/


You can do this:

function divideTextInSpans(text){
   return $.map(text.split(" "), function(word){
      return '<span class="word">'+word+'</span>';
   }).join(' ');
}

$(document).ready(function(){
   $(".divclass").each(function(){
      var newInnerHtml = divideTextInSpans($(this).text());
      $(this).html(newInnerHtml);
      $(this).find(".word").hover(function(){
          //Show your popup code here
          $(this).css("backgroundColor", "yellow"); //Highlight
      }, function(){
         //Hide your popup code here
          $(this).css("backgroundColor", ""); //Un-Highlight
      });
   });
});

What we're doing is put each word in the div in a separate span, and then bind a hover event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜