简体   繁体   English

Javascript动态事件处理,而不是Jquery

[英]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". 用于静态标签的“onclick”事件“选择”但不适用于动态创建的“选择”。 In other word i want to know what is alternate to .live of JQuery in Javascript. 换句话说,我想知道在Javascript中JQuery的.live的替代品。

Bind the event to a parent element, that already exists in the DOM: 将事件绑定到DOM中已存在的父元素:

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

JS Fiddle demo . JS小提琴演示

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. 将点击绑定到“更靠近” form的元素会更加明智,如果使用getElementById()而不是getElementByTagName() ,则更简单,因为您不必担心数字的索引你有约束力。

there's no need to bind the onclick handler to every select every time you add one. 每次添加时,都不需要将onclick处理程序绑定到每个选择。

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 ". jQuery的live函数使用“ 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. 从那里你需要检索事件的target / sourceElement并确定它是否是你关心的事件。

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. 您只在窗口加载时设置onclick。 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. 您需要做的就是将当前在window.onload中的代码放入命名函数中,然后在每次添加新选择时调用它。

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

}

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

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