jQuery 在 append() 上做一些事情
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7167085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
on append() do something
提问by clarkk
Is it possible to add some kind of an event/handler when an element is appended to the DOM...?
当元素被附加到 DOM 时,是否可以添加某种事件/处理程序......?
.click(), .change(), .keyup() etc. alike...
.click(), .change(), .keyup() 等等...
I need to get the height of an element as soon as it is appended and then set the height to another element
我需要在附加元素后立即获取元素的高度,然后将高度设置为另一个元素
回答by Dennis
You can override the default append method and cause it to trigger a custom append event. Then bind a handler to an element for that event: http://jsfiddle.net/H8ygx/
您可以覆盖默认的 append 方法并使其触发自定义 append 事件。然后将处理程序绑定到该事件的元素:http: //jsfiddle.net/H8ygx/
(function($) {
var origAppend = $.fn.append;
$.fn.append = function () {
return origAppend.apply(this, arguments).trigger("append");
};
})(jQuery);
$("div").bind("append", function() { alert('Hello, world!'); });
$("div").append("<span>");
回答by Scherbius.com
For that you can use the "DOMSubtreeModified" event. But it has limited compatibility. See: http://www.quirksmode.org/dom/events/#t18
为此,您可以使用“DOMSubtreeModified”事件。但它的兼容性有限。请参阅:http: //www.quirksmode.org/dom/events/#t18
$('#myDiv').live("DOMSubtreeModified", function() {
alert('something changed inside #myDiv div');
});
This event handler will work with all standard DOM modifying methods: appendTo(), insertBefore(), insertAfter(), etc.
此事件处理程序适用于所有标准 DOM 修改方法:appendTo()、insertBefore()、insertAfter() 等。
回答by FactualHarmony
The accepted answer will trigger the event on the container to which you are appending, which may not be what you want. Here is a version that will trigger the event on the element(s) you are appending. Note that this still doesn't correctly handle a function input to append().
接受的答案将触发您要附加到的容器上的事件,这可能不是您想要的。这是一个将在您附加的元素上触发事件的版本。请注意,这仍然无法正确处理 append() 的函数输入。
(function($)
{
var jqAppend = $.fn.append;
$.fn.append = function()
{
// Make a list of arguments that are jQuery objects
var appendages = $.makeArray(arguments).filter(function(arg)
{
return arg instanceof $;
});
// Call the actual function
var returnValue = jqAppend.apply(this, arguments);
// Trigger "append" event on all jQuery objects that were appended
for (var i = 0; i < appendages.length; ++i)
{
appendages[i].trigger('append');
}
return returnValue;
};
})(jQuery)
回答by BlackDivine
One way is that if you are doing append yourself make a function like:
一种方法是,如果您正在执行 append 自己的功能,请执行以下操作:
function do_append(elem)
{
elem.append('......');
// get height of your element
// set height of another element
}
or tell me if this method doesn't cut it for you :)
或者告诉我这个方法是否不适合你:)