无法将点击事件添加到列表项 [英] Cannot add click events to list items

查看:64
本文介绍了无法将点击事件添加到列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我首次尝试将Javascript与HTML结合使用。我正在尝试将点击事件添加到有序列表中的列表项中,但是关于我的操作方式却无法正常工作。有人可以帮我一下吗?

This is my first foray into using Javascript with HTML. I'm trying to add click events to the list items in an ordered list, but something about the way I'm doing it isn't working. Can somebody shed some light on this for me?

我在中创建了一个函数,该函数应将指定列表的列表项上的所有click事件委托给给定的函数,在该给定的函数中,我尝试使用列表项的文本来发出简单的警报。最终我想做更多,但是我只是想让简单的点击事件首先生效。

I create a function in my head that should delegate all click events on the list items of a specified list to a given function, and in that given function I try to raise a simple alert with the text of the list item. Eventually I want to do more, but I'm just trying to get the simple click events to work first.

<html>
    <head>
    <script type="text/javascript">
      // Attach an event handler to the 'topfriends' list to handle click events.
      function attachEventHandlerToList() {
          document.getElementById("#top4list").delegate("li", "click", function(clickEvent) {
              alert(this.innerHTML());
          });
        }
    </script>
</head>

<body>

    <div id="topfriends">
        <h3>Top 4 Most Friendable Friends</h3>
        <ol id="top4list" onload="attachEventHandlerToList()">
            <li>Brady</li>
            <li>Graham</li>
            <li>Josh</li>
            <li>Sean</li>
        </ol>
    </div>
</body>

推荐答案

让我们做这样的事情

<ul id="parent-list">
    <li id="a">Item A</li>
    <li id="b">Item B</li>
    <li id="c">Item C</li>
    <li id="d">Item D</li>
    <li id="e">Item E</li>
    <li id="f">Item F</li>
</ul>

现在为此编写JavaScript

Now write the javascript for this

<script type="text/javascript">
    // locate your element and add the Click Event Listener
    document.getElementById("parent-list").addEventListener("click",function(e) {
        // e.target is our targetted element.
                    // try doing console.log(e.target.nodeName), it will result LI
        if(e.target && e.target.nodeName == "LI") {
            console.log(e.target.id + " was clicked");
        }
    });
</script>

请参阅有关Javascript事件委托的这篇文章
http://davidwalsh.name/event-delegate

Please refer to this write-up on Javascript Event Delegates http://davidwalsh.name/event-delegate

下面链接是我创建的小提琴琴
http://jsfiddle.net/REtHT/

Also, below link is the fiddle that I created http://jsfiddle.net/REtHT/

希望这会有所帮助!

这篇关于无法将点击事件添加到列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆