Html 无法将点击事件添加到列表项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17636043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:05:58  来源:igfitidea点击:

Cannot add click events to list items

javascripthtmldom-events

提问by Daniel Brady

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?

这是我第一次尝试在 HTML 中使用 Javascript。我正在尝试将点击事件添加到有序列表中的列表项中,但我这样做的方式不起作用。有人可以为我解释一下吗?

I create a function in my headthat 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.

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

<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>

回答by Cooshal

Let's do something like this

让我们做这样的事情

<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>

Now write the javascript for this

现在为此编写javascript

<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>

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

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

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

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

hope this helps !

希望这可以帮助 !

回答by adeneo

delegate()is a deprecated jQuery method, and no such method exists in plain JS.
To attach an event handler in JS you'd use addEventListener, and for older versions of IE you'll need attachEventas well, that's why it's a little tricky with cross browser event handlers.
onclick, onmouseenteretc. will work in all browsers, but it's consider a better practice to use addEventListener/ attachEvent.

delegate()是不推荐使用的 jQuery 方法,纯 JS 中不存在这样的方法。
要在 JS 中附加一个事件处理程序,你会使用addEventListener,对于旧版本的 IE 你也需要attachEvent,这就是为什么跨浏览器事件处理程序有点棘手。
onclickonmouseenter等将在所有的浏览器,但它是考虑一个更好的做法是使用addEventListener/ attachEvent

Also, you have to run the script after the elements are added to the DOM, otherwise they are not available. The usual way is to insert the script after the elements, or use a DOM ready event handler.

此外,您必须在将元素添加到 DOM 后运行脚本,否则它们将不可用。通常的方法是在元素之后插入脚本,或者使用 DOM 就绪事件处理程序。

<html>
<head>
    <title>test</title>
</head>

<body>

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

<script type="text/javascript">
    var lis = document.getElementById("top4list").getElementsByTagName('li');

    for (var i=0; i<lis.length; i++) {
        lis[i].addEventListener('click', doStuff, false);
    }

    function doStuff() {
        alert( this.innerHTML );
    }
</script>
</body>

FIDDLE

小提琴

回答by Shapon Pal

Try this. It will work with child Node and Parent Node also.

尝试这个。它也适用于子节点和父节点。

 var visitorList = document.getElementById("visitor");
        visitorList.addEventListener("click", function (e) {
            var visitorId;
            if (e.target && e.target.nodeName == "LI") {
                visitorId = e.target.id;
                console.log(e.target.id);
            }
            if(e.target && e.target.nodeName == "H1") {
                visitorId = e.srcElement.parentElement.id;
                console.log(e.srcElement.parentElement.id);
            }
            //console.log(visitorId);
        });
<ul id="visitor">
        <li id="a" style="background: #CCCCCC; padding: 10px;"><h1 style="background: #437ba9;">Visitor A</h1></li>
        <li id="b"><h1>Visitor B</h1></li>
        <li id="c"><h1>Visitor C</h1></li>
        <li id="d"><h1>Visitor D</h1></li>
        <li id="e"><h1>Visitor E</h1></li>
        <li id="f"><h1>Visitor F</h1></li>
    </ul>

回答by Mehdi Benmoha

Hello why not doing it easier by replacing onLoad directy by onClick

你好,为什么不通过 onClick 直接替换 onLoad 来更容易

<script type="text/javascript">
function olClicked(){
alert(this.innerHTML());
}
</script>
<ol id="top4list" onClick="olClicked()">