开发者

jquery capture the word value

开发者 https://www.devze.com 2023-03-09 20:25 出处:网络
Is there a way to capture word value with jquery or javascript? in the example : Search: Quotes of the Month for May

Is there a way to capture word value with jquery or javascript? in the example :

Search: Quotes of the Month for May

When I click "Search:" or "Quotes" or any word, that I alert that word text?

Update :

This is what I meant :

http://jsfiddle.net/BE68L/

Is there a way I can get text value without wrapping i开发者_运维知识库t into some html element?


You cannot do it without wrapping it in HTML nodes. You can apply some Javascript magic to an "unwrapped text", which basically means a Textnode. This could look like:

$('#foo').contents().each(function(_, node) {
    var nodelist = node.textContent.split(/\s/).map(function( word ) {
        return $('<span>', {
            text: word + ' ',
            click: function() {
                alert( $(this).text() );
            }
        }).get(0);
    });

    $('#foo').empty().append(nodelist);
});

demo: http://jsfiddle.net/LFCWp/

I just wrote that down. There is still a ton of optimize potential, but it should give you a basic idea of how to accomplish it.


To find specific words in longer paragraphs you would have to create Range objects and TextRange's to find the coordinates of specific words in the paragraph. Once you have mapped the coordinates for each word, you could then match the window click event coordinates to the word that is within the range.

The question at Retrieving DOM textnode position has some similarities of what you are after.

In short, I think it should be perfectly doable to accurately get the word that is clicked, even in longer paragraphs, but it certainly isn't very easy, and for longer pieces of texts, it may end up being very inefficient.

edit for mozilla/webkit browsers, you could do it like this:

$(document).ready(function() {
    $("body").click(function(){
         var s = window.getSelection();
        s.modify('extend','backward','word');        
        var b = s.toString();

        s.modify('extend','forward','word');
        var a = s.toString();
        s.modify('move','forward','character');
         alert(b+a);

    });
});

example: http://jsfiddle.net/niklasvh/rD2uE/

It doesn't work on IE <= 8 though, you'd probably need to do a different kind of solution using the IE selections.

0

精彩评论

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