简体   繁体   English

JavaScript 获取每个单词的事件

[英]JavaScript get event on every word

Usually JavaScript binds events on DOM elements.通常 JavaScript 在 DOM 元素上绑定事件。 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?我觉得是多余的代码,有没有办法让代码更简洁一些?

Well, you could always write a JavaScript function to wrap every word for you: 好吧,你总是可以编写一个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; 
}

Of course, this assumes that the element has not other html in it. 当然,这假设元素中没有其他html。 You can combine this with Matti's suggestion to make the code much neater. 您可以将此与Matti的建议结合起来,使代码更加整洁。

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. 要以任何可行的方式执行此操作,您可能仍然需要将每个单词包装在一个单独的元素中,就像您正在做的那样,但您至少可以摆脱所有内联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? 您使用的是JS库还是没有使用JS库?

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). 编辑:由于你没有使用库, jQuery是一个受欢迎的选择(很受欢迎,被认为是SO上的陈词滥调,我想这说了些什么)。 Here's how you'd do it with jQuery: 以下是使用jQuery的方法:

http://jsfiddle.net/eKvdn/ (click the words) http://jsfiddle.net/eKvdn/ (点击话说)

It would be a very good idea to read more about it before using it, though. 不过,在使用它之前阅读更多关于它的信息是一个非常好的主意。

You can use JavaScript to find and wrap each word in a anchor or a span, and then add your onclick handler to that. 您可以使用JavaScript查找并包装锚点或范围中的每个单词,然后将onclick处理程序添加到该单词。 See how to get a word under cursor using JavaScript . 了解如何使用JavaScript在光标下获取单词

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM