jquery动态添加元素和动态添加click事件

博客介绍了如何在jQuery中动态添加HTML元素和为其绑定点击事件,特别强调了使用on()方法来确保动态创建的元素也能正确响应点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.动态追加HTML元素

 function appendText() {
  var txt1 = "<p>Text.</p>";               // Create element with HTML  
  var txt2 = $("<p></p>").text("Text.");   // Create with jQuery
  var txt3 = document.createElement("p");  // Create with DOM
  txt3.innerHTML = "Text.";
  $("body").append(txt1, txt2, txt3);      // Append the new elements 
}

2.获取HTML已有元素

 var div = document.getElementById('resource-id');//DOM方式,注意不是class,是ID
 var div = $('#resource-id');//div的id属性获取
 var div = $('div.resource-id');//div的class属性获取

3.静态元素添加点击事件

$("#elem").click(function(){ myFunction(); });
//或者DOM
document.getElementById('Button-id').onclick = myfunction;
//或者,通过属性
$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');

4.动态创建btn并添加事件

    html = "<span style=\"font-size:16px\">./" + path + "</span>";
    $('div.resource').append(html);
  
    var btn = document.createElement('button');
    var txt = document.createTextNode('test');
    btn.appendChild(txt);
    btn.setAttribute('type', 'button');
    btn.setAttribute('onclick', "callback(this)");//这个不好使,下面给出原因
    btn.setAttribute('id', 'button');
    div.append(btn);

5.不好使的原因

If you try to do something with the elements that are dynamically added to DOM using the jQuery click() method it will not work, because it bind the click event only to the elements that exist at the time of binding. To bind the click event to all existing and future elements, use the jQuery on() method. Check out the following example.

6.动态创建的元素添加click事件正确姿势

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Bind Click Event to Dynamically added Elements</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            $("ol").append("<li>list item <a href='javascript:void(0);' class='remove'>&times;</a></li>"); 
        });
        $(document).on("click", "a.remove" , function() { //这里通过指定资源ID
            $(this).parent().remove();
        });
    });
</script>
</head>
<body>
    <button>Add new list item</button>
    <p>Click the above button to dynamically add new list items. You can remove it later.</p>
    <ol>
        <li>list item</li>
        <li>list item</li>
        <li>list item</li>
    </ol>
</body> 
</html> 

参考《How to bind click event to dynamically created HTML elements in jQuery》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值