开发者

Jquery selectors: Select any words

How do i select with a selector all the words that are between two spaces? I don't want to select all the words with a complicated algorithm, i just 开发者_C百科want to apply a function when the mouse goes over a word in a div. And it is a e-book, this means, i need a efficient way to solve this..

Thank you very much


AFAIK textnodes are not suitable candidates for attaching events. Nor are they "selectable" by jQuery.

You can select the parent node of some text using the :contains() selector and attach events to that.

Update

What you can do is find your text's parent element and replace its inner HTML with some modified markup, eg

var parent = $(':contains("My Text")');
var text = parent.html();
parent.html(text.replace(/My Text/g, '<span class="hover-event">$&</span>'));

$('.hover-event').mouseenter(function(e) { ... });


The best answer that I could come up with was to use a regex to select each word in the div and surround it with <span> tags that had onmouseover events defined.

<html>
  <head>
    <script type="text/javascript">
      $(document).ready(function() {
        var text = $("#wordHoverable").html().trim();
        var newText = "";
        var wordRegex = /\w*/;     //Selects 'word characters' (alpha-numeric)
        var nonWordRegex = /\W*/;  //Selects all other characters

        var foundWord = text.match(wordRegex);
        while (foundWord != "") {
          newText += "<span onmouseover=\"hoverFunc('" + foundWord + "');\">" +
                foundWord + "</span>";
          text = text.replace(wordRegex, "");
          var nonWordChars = text.match(nonWordRegex);
          newText += nonWordChars;
          text = text.replace(nonWordRegex, "");
          foundWord = text.match(wordRegex);
        }
        $("#wordHoverable").html(newText);
      });

      function hoverFunc(text) {
        //Do whatever when their mouse is over the word
        $("#currentWord").html(text);
      }
    </script>
  </head>
  <body>
    <div>
      Current word: <span id="currentWord"></span>
    </div>
    <div id="wordHoverable">
      Hi there everyone.
    </div>
  </body>
</html>

Here's the same code in jsFiddle: http://jsfiddle.net/hpvtn/1/

This may not be very efficient to run on a large scale on-the-spot, but you could use this as sort of a "compiler" to convert easy-to-read, plain text in a <div> and convert it to the interactive text that you want.

Like Phil said, I don't think you can actually attach events to the individual words themselves unless you wrap them in <span> tags.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜