Usually JavaScript binds events on DOM elements. But I want to know on which word the user clicked. The familiar way for me is just wrap every words like 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 it's a redundant code, and is it possible to make code more concise?
Usually JavaScript binds events on DOM elements. But I want to know on which word the user clicked. The familiar way for me is just wrap every words like 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 it's a redundant code, and is it possible to make code more concise?
Share Improve this question edited Jan 14, 2023 at 17:26 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 7, 2011 at 19:17 megasmegas 21.8k12 gold badges82 silver badges134 bronze badges2 Answers
Reset to default 6Well, you could always write a JavaScript function to wrap every word for you:
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;
}
Of course, this assumes that the element has not other html in it. You can bine this with Matti's suggestion to make the code much neater.
To do this in any feasible way, you'll probably still have to wrap each word in a separate element like you're doing, but you can at least get rid of all the inline JavaScript.
Add your even listener to the parent element of the words. Any event that the word elements receive will bubble to the parent element, and you can look at the event target property to find out which word was clicked.
Are you using a JS library or are you working without one?
Edit: Since you're not using a library, jQuery is a popular choice (popular enough to be considered a cliché on SO, I guess that says something). Here's how you'd do it with jQuery:
http://jsfiddle/eKvdn/ (click the words)
It would be a very good idea to read more about it before using it, though.