javascript cloneNode with events

女生的网名这么多〃 提交于 2019-12-11 07:27:12

问题


I am working on a greasemonkey script for gmail where i need to make a copy of the "Inbox" link. Using cloneNode works ok, but i think there's an onclick event that gets attached to it at runtime. So, this is a two part question: 1. Is there a way to see what events are attached to a node? 2. Is there a way to copy those events as well? The closest thing i found was jQuery, and i am not ready to go there yet. Thanks!


回答1:


  1. Not unless it's set using the onclick attribute on the element.
  2. Not reliably (you can copy the onclick attribute, but whether that will continue to work depends on if it was used and what it does).

You're better off adding your own click handler, and then triggering that event on the original... Or simulating the behavior in some other way.




回答2:


I think we can solve this stuff using this theory:

We have NodeList in JS, also called liveLists. We can check whenever their length changes, addEvent the desired common events to the new element in list at (length-1).

What say....




回答3:


Here is the example using Nodelist for adding events.

<body>
        <div id="one" class="clones" style="background:red;width:100px;height:100px"></div>
    </body>

    <script>

        //Selecor based live list [Advantage]
        var nodeList = document.getElementsByClassName('clones')

        //Common Function for nodelist
        nodeList.addEvents = function(){
            nodeList.item(nodeList.length-1).addEventListener('click',function(){
                    console.log(this.id);
            });
        }
        nodeList.addEvents();

        //Making Clone
        var _clone  =  document.getElementsByTagName('div')[0].cloneNode(true);

        //Changing Id
        _clone.id="two"

        document.body.appendChild(_clone);
        nodeList.addEvents();
    </script>


来源:https://stackoverflow.com/questions/815642/javascript-clonenode-with-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!