简体   繁体   English

Jquery:仅在“单击时”追加一次 div

[英]Jquery: Append div only once 'on click'

I am trying to append a section to a div on the click of a button.我试图通过单击按钮将一个section附加到div

I want the section to be appended only on the first click, the code that I use below appends a section every time I click the div .我希望该section仅在第一次单击时附加,我在下面使用的代码每次单击div都会附加一个section

How should I go about this?我该怎么办?

$("#nextractorapply").click(function () {
    $("#main").append('<section id="nextractor" class="five"> </section>');  
});

You could use one() , which fires only once 你可以使用one() ,它只会触发一次

$("#nextractorapply").one('click', function () { 
    // executes only once

     $("#main").append('<section id="nextractor" class="five"> </section>');  
});

$("#nextractorapply").on('click', function () { 
    // executes every time

    // do other stuff
});

Use a conditional to determine if it's there. 使用条件来确定它是否存在。

$("#nextractorapply").click(function () {
    if($('#nextractor').length < 0){
        $("#main").append('<section id="nextractor" class="five"> </section>');
    }  
});

You can use some kind of a condition that prevents its appending multiple times. 您可以使用某种阻止其多次附加的条件。

var counter=0;
$("#nextractorapply").click(function () {
    if(counter<=0){
        $("#main").append('<section id="nextractor" class="five"> </section>');  
        counter++;
    }

    //YOUR OTHER STUFF THAT YOU NEED TO EXECUTE ON EVERY CLICK
});

You could use .unbind() 你可以使用.unbind()

$("#nextractorapply").unbind().click(function () {
    $("#main").append('<section id="nextractor" class="five"> </section>');  
});

You could set a variable and fire event if variable is set as true or false.如果变量设置为 true 或 false,您可以设置变量并触发事件。

var _clicked = false;

$('.element').click(function(){
  if(!_clicked){
   _clicked = true;
   console.log('event fired');
  }
})

You could check if the element has a default class, append html. 您可以检查元素是否具有默认类,并附加html。 For example you could add a class to html code like : class="first", and after first click remove that class. 例如,您可以将类添加到html代码,例如:class =“first”,并在第一次单击后删除该类。

A code something like this : 像这样的代码:

var element = $("#nextractorapply");
    if(element.hasClass("first")){
          $("#main").append('<section id="nextractor" class="five"> </section>');  
          element.removeClass("first");
    }

And then after first click, the "first" class will be removed from your html and Jquery will not append any further html. 然后在第一次单击后,“第一”类将从您的html中删除,Jquery将不会附加任何进一步的HTML。

$("#nextractorapply").click(function () {
    $("#main").empty().append('<section id="nextractor" class="five"> </section>');  
});

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

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