如何将文本附加到特定的 <div>
如果我知道<div>
的ID ?
例如,这是我的代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function appendDIV(idDIV, txt) {
$("#" + idDIV).append('<p>' + txt + '</p>');
}
appendDIV("content-01", "some text");
</script>
<div id="content-01" style="float: left; width: 150px; height: 150px; border: 2px solid red;"></div>
函数接受 <div>
的 ID和一些文字,但没有任何反应。
出了什么问题?
最佳答案
用于获取侧 div 中每个 p
的代码,您应该这样做
// Shorthand for $( document ).ready()
$(function() {
appendDIV("content-01", "some text");
//get all p element and go through each
$('#content-01 > p').each(function( index ) {
console.log( index + ": " + $( this ).text() );
console.log( "id of element" + $(this).attr('id'));
});
});
function appendDIV(idDIV, txt) {
$("#" + idDIV).append('<p>' + txt + '</p>');
}
<小时/>
在进行任何操作之前,您应该允许先加载 DOM,因此您应该在 jquery 中提供的 document.ready
方法中编写代码,该方法在 DOM 准备好时被调用
// Shorthand for $( document ).ready()
$(function() {
appendDIV("content-01", "some text");
});
添加上面的代码。就可以了。阅读此处:$( document ).ready()
关于javascript - 将文本添加到特定 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50880015/