javascript - 将文本添加到特定 DIV

标签 javascript jquery html

如何将文本附加到特定的 <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 的代码,您应该这样做

Working

// 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>');
  }
<小时/>

Working Demo

在进行任何操作之前,您应该允许先加载 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/

相关文章:

javascript - 如何在点击日期时获取 Bootstrap 日期选择器输入值并将该值复制到变量

javascript - 在 Laravel 中将 JSON 从 Controller 传输到 AngularJS

javascript - 从 Java 脚本/类型脚本中的对象数组获取属性数组

html - 当窗口最小化时,CSS 菜单会折叠

html - 位置 2 div 彼此相邻

substring - 如果存在特定的 url 子字符串并且如果为 null 则什么也没有

javascript - 使 JS 宽度为 : toggle has beautiful animation

javascript - jquery导航显示和隐藏多个页面

javascript - 隐藏/显示 div 轮廓

javascript - 沿相反方向旋转两个图像