Javascript AddEventListener只触发一次 [英] Javascript AddEventListener Fires only once

查看:1730
本文介绍了Javascript AddEventListener只触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML

  ... 
< div class =content-row> ;< div class =col-md-4>< / div>
< div class =col-md-4>
< form>
< div id ='undiv'class =form-group>< label for =uname>名称:< / label>< input id =unametype =text class =form-control/>< / div>
< div class =form-group>< label for =email>电子邮件(可选):< / label>< input id =emailtype =textclass =form-control/>< / div>
< div class =form-group>< label for =gamecode>游戏代码:< / label>< input id =gamecodetype =textclass = form-control/>< / div>
< div class =form-group pull-right>< input id =jointype =buttonvalue =Joinclass =btn btn-primary btn-lg btn btn- primary btn-lg/>< / div>
< / form>
< / div>< div class =col-md-4>< / div>
< / div>
....

body

 < script type ='text / javascript'> 
var uname = document.getElementById(uname);
var email = document.getElementById(email);
var gamecode = document.getElementById(gamecode);
var joinbtn = document.getElementById(join);
var notify = document.getElementById(notify);
var undiv = document.getElementById(undiv);
...


uname.addEventListener(blur,function(evt){
console.log('onblur');
var un = uname.value;
console.log(un);
if(un.length> = 2){
undiv.className + =has-success has-feedback;
undiv.innerHTML + ='< span id =markclass =glyphicon glyphicon-ok form-control-feedbackaria-hidden =true>< / span>';
}
else {
undiv.className + =has-error has-feedback;
undiv.innerHTML + ='< span id =markclass =glyphicon glyphicon-删除form-control-feedbackaria-hidden =true>< / span>';
}
//uname.value = un;
});

uname.addEventListener(focus,function(evt){
console.log('onfocus');
undiv.className =form-group;
var mark = document.getElementById(mark);
if(mark!= null){
mark.parentNode.removeChild(mark);
console.log(mark = + mark);
}
});
< / script>



uname onfocus onblur 事件只触发一次。



我有另外一个 eventListener 按钮点击事件上,它可以正常工作。



I不明白为什么焦点 blur eventListeners don'在事件发生时触发?

Chrome和Firefox上的调试器显示没有错误或警告......并且我不明白哪里出了问题?



http://jsfiddle.net/ddf5h2nu/

解决方案

最好的做法是在桌子上放一把尺子,如果您发现自己正在输入 element.innerHTML + =...,只需抓住标尺并拍打你的手背。

; - )



认真地说,使用 + = .innerHTML 之后的c>是非常具有破坏性的,也是不必要的,正如您所看到的那样会导致意想不到的结果。

其他答案显示了如何使用DOM创建方法来实现,这是一种好方法,但如果您想使用 HTML 标记,请使用 .insertAdjacentHTML( )而不是 .innerHTML

  uname.addEventListener(blur,function(evt){
console.log('onblur');
var un = uname.value;
console.log(un);
if(un.length> = 2){
undiv.className + =has-success has-feedback;
undiv.insertAdjacentHTML(beforeend,'< span id =标记class =glyphicon glyphicon-ok form-control-feedbackaria-hidden =true>< / span>');
}
else {
undiv.className + =has-error has-feedback;
undiv.insertAdjacentHTML(beforeend,'< spa nid =markclass =glyphicon glyphicon-remove form-control-feedbackaria-hidden =true>< / span>');
}
//uname.value = un;
});

您会注意到第一个参数是beforeend,第二个是你的HTML。 .insertAdjacentHTML()方法接受四个不同的字符串作为第一个参数。它们如下:


  • beforebegin (把标记元素之前)

  • afterbegin (将标记放在元素的开头)

  • beforeend (将标记放在元素末尾) li>
  • afterend (将元素放在元素后面)
  • ul>

    因此,有四个位置可以插入相对于调用方法的元素的HTML。这些不会破坏任何现有的元素,这就是为什么它比 .innerHTML 更好。


    I have the following HTML

    ...
        <div class="content-row"><div class="col-md-4"></div>
                <div class="col-md-4">
                    <form>
                        <div id='undiv' class="form-group"><label for="uname">Name:</label><input id="uname" type="text" class="form-control"/></div>
                        <div class="form-group"><label for="email">Email (optional):</label><input id="email" type="text" class="form-control" /></div>
                        <div class="form-group"><label for="gamecode">Game Code:</label><input id="gamecode" type="text" class="form-control" /></div>
                        <div class="form-group pull-right"><input id="join" type="button" value="Join" class="btn btn-primary btn-lg btn btn-primary btn-lg" /></div>
                    </form>
                </div><div class="col-md-4"></div>
        </div>
    ....
    

    Javascript below the HTML in body

    <script type='text/javascript'>
                var uname = document.getElementById("uname");
                var email = document.getElementById("email");
                var gamecode = document.getElementById("gamecode");
                var joinbtn = document.getElementById("join");
                var notify = document.getElementById("notify");
                var undiv = document.getElementById("undiv");
    ...
    
    
        uname.addEventListener("blur",function(evt) {
                    console.log('onblur');
                    var un = uname.value;
                    console.log(un);
                    if(un.length >= 2) {
                        undiv.className += " has-success has-feedback";
                        undiv.innerHTML += '<span id="mark" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>';
                    }
                    else {
                        undiv.className += " has-error has-feedback";
                        undiv.innerHTML += '<span id="mark" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>';
                    }
                    //uname.value = un;
                });
    
                uname.addEventListener("focus",function(evt) {
                    console.log('onfocus');
                    undiv.className = "form-group";
                    var mark = document.getElementById("mark");
                    if(mark !=null) {
                        mark.parentNode.removeChild(mark);      
                        console.log("mark="+mark);  
                    }   
                });
        </script>
    

    The uname on onfocus and onblur events fire only once.

    I have another eventListener on the button click event and it works fine.

    I don't understand why focus and blur eventListeners don't fire whenever the event happens ?

    The debugger on Chrome and Firefox show no errors or warning... And I don't understand What is going wrong ?

    http://jsfiddle.net/ddf5h2nu/

    解决方案

    A good practice is to keep a ruler on your desk, and if you find yourself typing element.innerHTML += "...", just grab the ruler and smack the back of your hand.

    ;-)

    Seriously though, using += after .innerHTML is very destructive and unnecessary and as you can see leads to unexpected results.

    The other answer shows how to do it with DOM creation methods, which is a good way, but if you want to use HTML markup, then use .insertAdjacentHTML() instead of .innerHTML.

    uname.addEventListener("blur",function(evt) {
        console.log('onblur');
        var un = uname.value;
        console.log(un);
        if(un.length >= 2) {
            undiv.className += " has-success has-feedback";
            undiv.insertAdjacentHTML("beforeend", '<span id="mark" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
        }
        else {
            undiv.className += " has-error has-feedback";
            undiv.insertAdjacentHTML("beforeend", '<span id="mark" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
        }
        //uname.value = un;
    });
    

    You'll notice that the first argument is "beforeend" and the second is your HTML. The .insertAdjacentHTML() method accepts four different strings as the first argument. They are as follows:

    • "beforebegin" (put the markup before the element)
    • "afterbegin" (put the markup inside the element at the beginning)
    • "beforeend" (put the markup inside the element at the end)
    • "afterend" (put the markup after the element)

    So there are four positions where the HTML can be inserted relative to the element on which the method is invoked. These don't destroy any existing elements, which is why it's better than .innerHTML.

    这篇关于Javascript AddEventListener只触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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