简体   繁体   中英

Javascript Dynamic Event Handling, Not Jquery

here is my code

<html>
    <head>
    <script type="text/javascript">
    window.onload = function(){
        sel = document.getElementsByTagName('select');
        for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
    }
    </script>
    </head>
    <body>
    <div id="ss"></div>
    <select></select>
    <input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'))"/>

    </body>
</html>

"onclick" event working for static tag "Select" but not working for Dynamically created "Select". In other word i want to know what is alternate to .live of JQuery in Javascript.

Bind the event to a parent element, that already exists in the DOM:

document.body.addEventListener('click', function (e) {
  if (e.target.tagName.toLowerCase() == 'select') {
    alert('You clicked a select!');
  }
});

JS Fiddle demo .

It would be slightly more sensible to bind the click to an element 'closer' to the form , and if you use getElementById() rather than getElementByTagName() it's more simple, since you don't have to worry about the index of the number you're binding to.

there's no need to bind the onclick handler to every select every time you add one.

I am not going to retype your whole page, but you'll see what's going on by reading following snippets:

function handler() {
    alert('You clicked a select!');
}

window.onload = function(){
    sel = document.getElementsByTagName('select');
    for(int i= 0; i < sel.length; i++) {
        sel[i].onclick = handler;
    }
}

function addSelect() {
    var slt = document.createElement("select");
    document.getElementById('ss').appendChild(slt);
    slt.onclick = handler;
}

<input type="button" onclick="addSelect();"/>

jQuery's live function works by using " Event Delegation ". The basic idea is that you bind a listener on a parent element, which is guaranteed to exist when the page loads. Any element below that ( with the exception of some ) will fire off an event which can be caught by the parent listener. From there you would need to retrieve the target/sourceElement of the event and determine whether or not it's one you care about.

Something like this will work for listening to clicks. Just make sure that any new elements you are adding are located within the proper parent container and have an attribute which distinguishes them from the rest of the clickable elements.

<html>
<head>
    <script type="text/javascript">
        window.onload = function(){
            // get the relevant container
            var eventContainer = document.getElementById("EventContainer");

            // bind a click listener to that container
            eventContainer.onclick = function(e){

                // get the event
                e = e || window.event;

                // get the target
                var target = e.target || e.srcElement;

                // should we listen to the click on this element?
                if(target.getAttribute("rel") == 'click-listen')
                {
                    alert("You clicked something you are listening to!");
                }// if
            };
        };
    </script>
</head>
<body>
<div id="EventContainer">
    <input type="button" rel="click-listen" name="myButton" value="Listening to this button." />
    <input type="button" name="anotherButton" value="Not listening." />
    <p>I'm also listening to this a element: <a href="#" rel="click-listen">listening to this</a></p>
</div>
</body>
</html>

You're only setting the onclick when the window loads. All you need to do is put the code currently in the window.onload into a named function, then call it every time you add a new select.

here's the dumb way to do it:

<html>
    <head>
    <script type="text/javascript">

    function update () {
        sel = document.getElementsByTagName('select');
        for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
    }
    window.onload = update;

    </script>
    </head>
    <body>
    <div id="ss"></div>
    <select></select>
    <input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'));update();"/>

    </body>
</html>

You can use a cross-browser solution as shown below to add event handler dynamically

sel = document.getElementsByTagName('select');
for( i=0; i<sel.length; i++){
    if (sel[i].addEventListener){
        sel[i].addEventListener("click", clickHandler, false);
    } else if (sel[i].attachEvent){
        sel[i].attachEvent("onclick", clickHandler);
    }else{
        sel[i].onclick = clickHandler;
    }
}

function clickHandler(event){

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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