我有一个<div>
元素,除非某些功能被激活,否则它不会出现在页面上。我希望在页面上显示后删除此<div>
。
当且仅当添加了此<div>
元素时,如何运行我的JavaScript代码?
我是新手,非常感谢你的帮助。感谢。
PS。元素由jquery生成,只有classname。
详细说明:
我在现有的Web应用程序中实现excel导出 我正在使用围绕搜索过滤器的表单和ajaxgrid gridstate。 此表单将提交给具有相应视图模型的控制器。
我提交表单的代码是:
$(function () {
$('div.btn-group #export-citizen-list').on('click', function () {
var gridstate = $('#citizenIndexGrid').ajaxgrid('getState');
var form = $('#create-citizen-csv-file');
// add ajaxgrid state to post data
$.each(gridstate, function (k, v) {
form.addAjaxgridHidden(k, v);
});
// submit entire form, with ajaxgrid state
form.submit();
// remove all hiddenfields that belongs to ajaxgrid
form.find(":hidden.ajaxgrid").remove();
document.getElementById("filterSearch").className = "default ui-button ui-widget ui-state-default ui-corner-all";
$('#filterSearch').removeAttr('disabled');
// function that removes unwanted <div> ---->$('.ajaxWorkingNotification').slideUp();
})
jQuery.fn.addAjaxgridHidden = function (name, value) {
return this.each(function () {
var input = $('<input>').attr('type', 'hidden').attr('name', name).attr('class', 'ajaxgrid').val(value);
$(this).append($(input));
});
};
});
当我提交表单时,会下载excel并在DOM中插入不需要的<div>
。问题是我不知道在这种情况下何时返回回发。因此我不知道何时插入<div>
。
希望这能澄清我的问题。
答案 0 :(得分:1)
你可以这样做。
// Assuming your element is created by this line ...
$(".your_elements_class_name").ready(function() {
// write code here
// this is executed after the element is created and added to DOM
})
答案 1 :(得分:0)
您可以通过在DOM节点插入事件上实现侦听器来实现。
有关如何检测DOM节点插入的解释here&amp;用于演示其工作原理的纯JavaScript代码
如果您喜欢jQuery版本,那么这是我从上面链接翻译的示例代码。
HTML:
<input type="button" id="addme" value="Add"/>
<div id="container">
</div>
CSS:
@keyframes nodeInserted {
from { opacity: 0.99; }
to { opacity: 1; }
}
#container div#mydiv {
animation-duration: 0.001s;
animation-name: nodeInserted;
}
使用Javascript:
$(function () {
$('#addme').click(function () {
var div = $('<div/>').attr('id', 'mydiv').html("Hello");
$('#container').append(div);
});
var handler = function (e) {
if (e.originalEvent.animationName == "nodeInserted")
alert("An HTMLElement has been inserted to DOM tree !")
};
var eventSignature = 'MSAnimationStart';
if ($.browser.webkit) eventSignature = 'webkitAnimationStart';
if ($.browser.mozilla) eventSignature = 'animationstart';
$(document).on(eventSignature, handler);
});