[英]How can I observe changes to my DOM and react to them with jQuery?
I have this function where I toggle a class on click, but also append HTML to an element, still based on that click.我有这个功能,我在点击时切换一个类,但也将 HTML 附加到一个元素,仍然基于点击。
The problem is that now, I'm not listening to any DOM changes at all, so, once I do my first click, yup, my content will be added, but if I click once again - the content gets added again, because as far as this instance of jQuery is aware, the element is not there.问题是,现在,我根本没有听到任何 DOM 更改,所以,一旦我第一次点击,是的,我的内容将被添加,但是如果我再次点击 - 内容会再次添加,因为作为就这个 jQuery 实例而言,该元素不存在。
Here's my code:这是我的代码:
(function($) {
"use strict";
var closePluginsList = $('#go-back-to-setup-all');
var wrapper = $('.dynamic-container');
$('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
$('.setup-theme-container').toggleClass('plugins-list-enabled');
if ( !wrapper.has('.plugins-container') ){
var markup = generate_plugins_list_markup();
wrapper.append(markup);
} else {
$('.plugins-container').hide();
}
});
//Below here, there's a lot of code that gets put into the markup variable. It's just generating the HTML I'm adding.
})(jQuery);
Someone suggested using data attributes, but I've no idea how to make them work in this situation.有人建议使用数据属性,但我不知道如何使它们在这种情况下工作。
Any ideas?有任何想法吗?
You could just do something like adding a flag and check for it before adding your markup.您可以执行一些操作,例如添加标志并在添加标记之前检查它。
var flag = 0;
$('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
$('.setup-theme-container').toggleClass('plugins-list-enabled');
if ( !wrapper.has('.plugins-container') ){
var markup = generate_plugins_list_markup();
if(flag == 0){
wrapper.append(markup);
flag = 1;
}
} else {
$('.plugins-container').hide();
}
});
If you want to add element once only on click then you should make use of .one() and put logic you want to execute once only in that handler.如果您只想在单击时添加元素一次,那么您应该使用.one()并将您只想在该处理程序中执行一次的逻辑放入。
Example :例子 :
$(document).ready(function(){
$("p").one("click", function(){
//this will get execute once only
$(this).animate({fontSize: "+=6px"});
});
$("p").on("click", function(){
//this get execute multiple times
alert('test');
});
});
html html
<p>Click any p element to increase its text size. The event will only trigger once for each p element.</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.