插入 jQuery 后更新 DOM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1550761/
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
Update DOM after insert in jQuery
提问by astrofrog
Let's say I use jQuery to load new content into a specific DIV element. If I now want to catch events from inside that DIV element, I assume the DOM has to be updated somehow? What is the best way to deal with this?
假设我使用 jQuery 将新内容加载到特定的 DIV 元素中。如果我现在想从该 DIV 元素内部捕获事件,我认为必须以某种方式更新 DOM?处理这个问题的最佳方法是什么?
Edit: Here is an example of what I mean:
编辑:这是我的意思的一个例子:
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script>
$(document).ready(function(){
$(".edit").click(function(){
$(this).parent().load("edit");
});
$(".view").click(function(){
$(this).parent().load("view");
});
});
</script>
</head>
<body>
<div class='someid'>
<input type='submit' class='edit' value='Edit'>
</div>
</body>
</html>
where a file edit
at the same level contains
其中edit
同一级别的文件包含
<input type='submit' class='view' value='View'>
and a file 'view' contains
和文件“视图”包含
<input type='submit' class='edit' value='Edit'>
If you try this out you will see that when you first press Edit, the button changes to View, but then it doesn't change anymore. Why is this?
如果你试试这个,你会看到当你第一次按下 Edit 时,按钮变成了 View,但它不会再改变了。为什么是这样?
回答by Luis Alvarado
Since jQuery 1.7.x the .live()method is deprecated. Use .on()to attach event handlers. If you are using an older version you should use .delegate()in preference to .live().
从 jQuery 1.7.x 开始,.live()方法已被弃用。使用.on()附加事件处理程序。如果您使用的是旧版本,则应优先使用.delegate()而不是.live()。
As mentioned in the help, the format does not change a lot like shown in this example:
正如帮助中提到的,格式没有像这个例子中显示的那样改变很多:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
So since 1.7.x, both, delegateand livehave been superseeded by on.
如此以来1.7.x,两者委托和现场由已superseeded上。