Jquery:在“点击”上只附加一次div
我试图通过单击按钮将一个section
附加到div
。
我希望该section
仅在第一次单击时附加,我在下面使用的代码每次单击div
都会附加一个section
。
我该怎么办呢?
$("#nextractorapply").click(function () { $("#main").append(' '); });
你可以使用one()
,它只会触发一次
$("#nextractorapply").one('click', function () { // executes only once $("#main").append(' '); }); $("#nextractorapply").on('click', function () { // executes every time // do other stuff });
使用条件来确定它是否存在。
$("#nextractorapply").click(function () { if($('#nextractor').length < 0){ $("#main").append(' '); } });
您可以使用某种阻止其多次附加的条件。
var counter=0; $("#nextractorapply").click(function () { if(counter<=0){ $("#main").append(' '); counter++; } //YOUR OTHER STUFF THAT YOU NEED TO EXECUTE ON EVERY CLICK });
你可以使用.unbind()
$("#nextractorapply").unbind().click(function () { $("#main").append(' '); });
您可以检查元素是否具有默认类,并附加html。 例如,您可以将类添加到html代码,例如:class =“first”,并在第一次单击后删除该类。
像这样的代码:
var element = $("#nextractorapply"); if(element.hasClass("first")){ $("#main").append(' '); element.removeClass("first"); }
然后在第一次单击后,“第一”类将从您的html中删除,Jquery将不会附加任何进一步的HTML。