JavaScript gets an event for every word

Typically, JavaScript binds events to DOM elements. But I want to know what word the user clicked on. The famous way for me is to simply wrap all the words, as here:

<a href="javascript:onClick()">And</a> <a href="javascript:onClick()">now</a> <a href="javascript:onClick()">the</a>
<a href="javascript:onClick()">kung</a> <a href="javascript:onClick()">pao</a> <a href="javascript:onClick()">chicken</a>.

I think this is redundant code, and is it possible to make the code more concise? Thanks

+3
source share
3 answers

To do this in any way possible, you probably still have to wrap each word in a separate element, as you do, but you can at least get rid of all the built-in JavaScript.

. , , , target target, , .

JS ?

: , jQuery ( , SO, , - ). jQuery:

http://jsfiddle.net/eKvdn/ ( )

, .

+4

, JavaScript, :

function wrapWords(element) {
    var html = element.innerHTML;
    var words = html.split(/ /);
    var newHtml = '';

    for (var i = 0; i < words.length; i++) {
        newHtml += '<span>' + words[i] + '</span> ';
    }

    element.innerHTML = newHtml; 
}

, , html. , .

+6

You can use JavaScript to search and wrap each word in an anchor or in between, and then add an onclick handler to it. See how to get the word under the cursor using JavaScript .

+2
source

All Articles