繁体   English   中英

新创建元素上的事件处理程序

[英]Event Handlers On Newly Created Elements

我有一个带有许多文本区域的Web应用程序,并且可以根据需要添加更多内容。

当您将焦点从一个文本区域转移到另一个文本区域时,焦点区域会设置为更大的动画,其余区域会缩小。

当页面加载时,它可以完美处理html文件中最初四个框的动画,但是当您单击按钮添加更多文本区域时,动画将无法容纳这些新元素……也就是说,除非您放置初始查询在一个函数中,然后从与按钮绑定的addelement函数中调用该函数。

但是,当您执行此操作时,它会查询添加新元素的次数。 因此,如果您快速添加(例如10个)新的文本区域,则下次您将焦点放在任何文本区域时,查询将运行10次。

是我的设计或jQueries实现中的问题吗? 如果是前者,我将如何设计更好;如果是后者,我将如何解决?

我尝试将代码分解为相关的位...我尝试了从焦点和模糊到按键的所有操作,最后单击即可。

html ::

<html>
<head>
    <link rel="stylesheet" type="text/css" href="./sty/sty.css" />      
    <script src="./jquery.js"></script>
<script>
    $().ready(function() {
        var $scrollingDiv = $("#scrollingDiv");

        $(window).scroll(function(){            
            $scrollingDiv
                .stop()
                //.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );            
                .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "fast" );          
        });
    });
</script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>boxdforstacks</title>
</head>
<body>
    <div class="grid">

        <div class="col-left" id="left">
                        <div class="module" id="scrollingDiv">
            <input type="button" value="add" onclick="addele()" />
            <input type="button" value="rem" onclick="remele()" />
            <p class="display">The value of the text input is: </p>
            </div>
      </div> <!--div class="col-left"-->


        <div class="col-midd">
            <div class="module" id="top">
                            <p>boxa</p>
                            <textarea class="tecksd" placeholder="begin typing here..." id="boxa" ></textarea>
                            <p>boxb</p>
                            <textarea class="tecksd" placeholder="begin typing here..." id="boxb"></textarea>
                            <p>boxc</p>
                            <textarea class="tecksd" placeholder="begin typing here..." id="boxc"></textarea>
                            <p>boxd</p>
                            <textarea class="tecksd" placeholder="begin typing here..." id="boxd"></textarea>
      </div>
        </div> <!--div class="col-midd"-->
    </div> <!--div class="grid"-->

</body>
</html>
    <script type="text/javascript" src="boxd.js"></script> 

js:

function onit(){
    $('textarea').on('keyup change', function() {
        $('p.display').text('The value of the text input is: ' + $(this).val());
    });

}
$('textarea').on("click",function(){
        //alert(this.id.substring(0,3));
        if ( this.id.substring(0,3)  == 'box' ){
                        $('textarea').animate({ height: "51" }, 1000);
                        $(this).animate({ height: "409" }, 1000);
        } else {
                        $('textarea').animate({ height: "51" }, 1000);
        }
}
    );
var boxfoc="";
var olebox="";
var numb = 0;
onit();

function addele() {

  var tops = document.getElementById('top');
    var num = numb + 1;
    var romu = romanise(num);

  var newbox = document.createElement('textarea');
  var newboxid = 'box'+num;

  newbox.setAttribute('id',newboxid);
    newbox.setAttribute('class','tecksd');
    newbox.setAttribute('placeholder','('+romu+')');

  tops.appendChild(newbox);

    numb = num;
    onit();
} //addele(), add element




function remele(){

  var tops = document.getElementById('top');
  var boxdone = document.getElementById(boxfoc);
  tops.removeChild(boxdone);
} // remele(), remove element



function romanise (num) {
    if (!+num)
        return false;
    var digits = String(+num).split(""),
        key = ["","c","cc","ccc","cd","d","dc","dcc","dccc","cm",
               "","x","xx","xxx","xl","l","lx","lxx","lxxx","xc",
               "","i","ii","iii","iv","v","vi","vii","viii","ix"],
        roman = "",
        i = 3;
    while (i--)
        roman = (key[+digits.pop() + (i * 10)] || "") + roman;
    return Array(+digits.join("") + 1).join("M") + roman;
} // romanise(), turn numbers into roman numerals

css:

.tecksd {
    width: 97%;
    height: 51;
    resize: none;
    outline: none;
    border: none;
    font-family: "Lucida Console", Monaco, monospace;
    font-weight: 100;
    font-size: 70%;
    background: white;
/*  box-shadow: 1px 2px 7px 1px #0044FF;*/
}

.tecksded {
    width: 97%;
    resize: none;
    outline: none;
    border: none;
    overflow: auto;
    position: relative;
    font-family: "Lucida Console", Monaco, monospace;
    font-weight: 100;
    font-size: 70%;
    background: white;
/*  box-shadow: 1px 2px 7px #FFDD00;*/
}


/*#postcomp {
    width: 500px;
}*/


* {
  @include box-sizing(border-box);
}

$pad: 20px;

.grid {
  background: white;
  margin: 0 0 $pad 0;

  &:after {
    /* Or @extend clearfix */
    content: "";
    display: table;
    clear: both;
  }
}

[class*='col-'] {
    float: left;
  padding-right: $pad;
  .grid &:last-of-type {
    padding-right: 0;
  }
}
.col-left {
    width: 13%;
}
.col-midd {
    width: 43%;
}
.col-rght {
    width: 43%;
}

.module {
  padding: $pad;


}

/* Opt-in outside padding */
.grid-pad {
  padding: $pad 0 $pad $pad;
  [class*='col-']:last-of-type {
    padding-right: $pad;
  }
}

body {
    padding: 10px 50px 200px;
  background: #FFFFFF;
  background-image: url('./backgrid.png');

}
h1 {
  color: black;
    font-size: 11px;
    font-family: "Lucida Console", Monaco, monospace;
    font-weight: 100;
}
p {
  color: white;
    font-size: 11px;
    font-family: "Lucida Console", Monaco, monospace;
    font-weight: 100;
}

您应该使用以下内容:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on("click", "textarea", function () {
    event.preventDefault();
    alert('testlink'); 
});

由于textarea是动态添加的,因此您需要使用事件委托来注册事件处理程序。

尝试

$(document).on('click', 'textarea', function() {
    // do something
});

问题是您仅在页面加载时绑定文本区域。 我用工作代码制作了一个JSFiddle: http : //jsfiddle.net/VpABC/

这是我更改的内容:我包装了:

$('textarea').on("click", function () {
        //alert(this.id.substring(0,3));
        if (this.id.substring(0, 3) == 'box') {
            $('textarea').animate({
                height: "51"
            }, 1000);
            $(this).animate({
                height: "409"
            }, 1000);
        } else {
            $('textarea').animate({
                height: "51"
            }, 1000);
        }
    });

在一个函数中,它看起来像这样:

function bindTextAreas() {
    $('textarea').unbind("click");
    $('textarea').on("click", function () {
        //alert(this.id.substring(0,3));
        if (this.id.substring(0, 3) == 'box') {
            $('textarea').animate({
                height: "51"
            }, 1000);
            $(this).animate({
                height: "409"
            }, 1000);
        } else {
            $('textarea').animate({
                height: "51"
            }, 1000);
        }
    });
}
bindTextAreas();

它的作用是,每当您创建新的textarea时,您就可以调用此函数bindTextAreas。 这将取消绑定所有当前事件,而不是重新绑定它们。 这样可以使您的新文本区域具有单击处理程序设置。

调用此函数的位置在addele函数中,如下所示:

function addele() {

    var tops = document.getElementById('top');
    var num = numb + 1;
    var romu = romanise(num);

    var newbox = document.createElement('textarea');
    var newboxid = 'box' + num;

    newbox.setAttribute('id', newboxid);
    newbox.setAttribute('class', 'tecksd');
    newbox.setAttribute('placeholder', '(' + romu + ')');

    tops.appendChild(newbox);

    numb = num;
    onit();
    bindTextAreas();
} //addele(), add element

注意bindTextAreas(); 底部附近的线。 这将重新加载所有点击处理程序。

暂无
暂无

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

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