在追加元素后刷新DOM [英] refresh DOM after append element

查看:675
本文介绍了在追加元素后刷新DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已解决:

主要问题在于:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

jquery太旧了我认为

jquery was too old I think

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

已解决问题:)

为何提醒追加DOM后不起作用?点击它后应显示bla bla。

Why alert doesn't work after append DOM? Should shows "bla bla" after click on it.

<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('#main_body').append("<h1>Hello</h1><input id=\"but\" type=\"button\">Click");
    $( "#but" ).on( "click", function() {
        alert( "bla bla" );
    });    
});   
</script> 
</head>

<body id="main_body">    
</body>
</html>


推荐答案

对于动态添加的元素,您需要事件委派,使用jQuery on()上的其他版本,您可以将事件委托给动态添加元素的静态父级。在您的情况下,您可以使用 #main_body

For dynamically added elements you need event delegation, use the other version on jQuery on(), you can delegate event to static parent of the dynamically added elements. In your case you can use #main_body

$('#main_body').on( "click", "#but", function() {
    alert( "bla bla" );
});    




委托事件的优势在于它们可以处理来自$ b $的事件b后来添加到文档中的后代元素。通过
选择在附加
委托事件处理程序时保证存在的元素,您可以使用委托事件到
,避免频繁附加和删除事件处理程序,< a href =https://api.jquery.com/on/> jQuery Docs

您的代码有效 here 因为您在绑定事件之前添加动态元素但使用事件委托将释放您用于添加动态元素的序列。

Your code works here as it is because you are adding the dynamically element before binding the event but using event delegation will free you from the sequence you use to add the dynamic elements.

这篇关于在追加元素后刷新DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆