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'>×</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》