Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将文本添加到特定DIV_Javascript_Jquery_Html - Fatal编程技术网

Javascript 将文本添加到特定DIV

Javascript 将文本添加到特定DIV,javascript,jquery,html,Javascript,Jquery,Html,如果我知道文本的ID,如何将文本附加到特定的文本? 例如,下面是我的代码: 函数appendDIVidDIV,txt{ $+idDIV.append''+txt+''; } 附录1-01,部分文本; 代码得到每一个p在侧div你应该这样做 如上所述添加代码。那就行了。在这里阅读:你也可以考虑一个自定义触发器,传递值,例如如果你想在div上点击一个事件,然后插入一些东西: $'body'。在'appenddiv',functionevent,idDIV,txt上{ $+idDIV.append

如果我知道文本的ID,如何将文本附加到特定的文本? 例如,下面是我的代码:

函数appendDIVidDIV,txt{ $+idDIV.append''+txt+'

'; }
附录1-01,部分文本; 代码得到每一个p在侧div你应该这样做


如上所述添加代码。那就行了。在这里阅读:

你也可以考虑一个自定义触发器,传递值,例如如果你想在div上点击一个事件,然后插入一些东西:

$'body'。在'appenddiv',functionevent,idDIV,txt上{ $+idDIV.append''+txt+'

'; }; //在代码后面的部分: $.mydiv组。单击,函数{ 让myid=$this.attr'id'; 让mytext=myid+:一些文本; $'body'。触发'appenddiv',[myid,mytext]; };
你怎么称呼appendDIV的?调用函数时容器是否存在,如果不存在,它将无法工作。appendDIVcontent-01,一些文本;当你调用这个函数时它存在吗?您可以通过测试$+idDIV.length进行检查,如果它是0,那么它还不存在。此外,还可以添加as,这将有助于更好地诊断问题。由于它在这里工作得很好,因此可能有助于制作一个示例来演示问题。问题似乎取决于加载JavaScript的位置:例如,在脚本末尾的VS中。请参阅和等@Josef-添加了答案和演示,这将帮助您浏览jquery文档一次
// 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>');
  }
// Shorthand for $( document ).ready()
$(function() {
    appendDIV("content-01", "some text");
});